From 2f6f90a3310024417298db5a485ab7f0a387cd6b Mon Sep 17 00:00:00 2001 From: Yan Chen <48968912+chenyan-dfinity@users.noreply.github.com> Date: Tue, 12 Dec 2023 10:29:49 -0800 Subject: [PATCH] refine IDLValue::Blob display (#497) * refine IDLValue::Blob display * fix * fix * fix --- rust/candid/src/pretty/candid.rs | 16 ++++++++++++---- rust/candid_parser/tests/parse_value.rs | 2 +- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/rust/candid/src/pretty/candid.rs b/rust/candid/src/pretty/candid.rs index ea13fe98..1e2d8439 100644 --- a/rust/candid/src/pretty/candid.rs +++ b/rust/candid/src/pretty/candid.rs @@ -340,8 +340,15 @@ pub mod value { Opt(v) => write!(f, "opt {v:?}"), Blob(b) => { write!(f, "blob \"")?; - for v in b.iter() { - write!(f, "{}", &pp_char(*v))?; + let is_ascii = b.iter().all(|c| (0x20u8..=0x7eu8).contains(c)); + if is_ascii { + for v in b.iter() { + write!(f, "{}", pp_char(*v))?; + } + } else { + for v in b.iter() { + write!(f, "\\{v:02x}")?; + } } write!(f, "\"") } @@ -350,6 +357,7 @@ pub mod value { write!(f, "blob \"")?; for v in vs.iter() { match v { + // only here for completeness. The deserializer should generate IDLValue::Blob instead. Nat8(v) => write!(f, "{}", &pp_char(*v))?, _ => unreachable!(), } @@ -433,13 +441,13 @@ pub mod value { } pub fn pp_char(v: u8) -> String { - if (0x20..=0x7e).contains(&v) && v != 0x22 && v != 0x27 && v != 0x60 && v != 0x5c { + let is_ascii = (0x20u8..=0x7eu8).contains(&v); + if is_ascii && v != 0x22 && v != 0x27 && v != 0x60 && v != 0x5c { std::char::from_u32(v as u32).unwrap().to_string() } else { format!("\\{v:02x}") } } - pub fn pp_value(depth: usize, v: &IDLValue) -> RcDoc { use IDLValue::*; if depth == 0 { diff --git a/rust/candid_parser/tests/parse_value.rs b/rust/candid_parser/tests/parse_value.rs index 589c80d5..65c23769 100644 --- a/rust/candid_parser/tests/parse_value.rs +++ b/rust/candid_parser/tests/parse_value.rs @@ -58,7 +58,7 @@ fn parse_string_literals() { ] ); let args = parse_args("(blob \"DIDL\\00\\01\\7d\\80\\00\")"); - assert_eq!(format!("{args}"), r#"(blob "DIDL\00\01}\80\00")"#); + assert_eq!(format!("{args}"), r#"(blob "\44\49\44\4c\00\01\7d\80\00")"#); let args = parse_args_err("(\"DIDL\\00\\01\\7d\\80\\00\")"); assert_eq!( format!("{}", args.unwrap_err()),