Skip to content

Commit

Permalink
refine IDLValue::Blob display (#497)
Browse files Browse the repository at this point in the history
* refine IDLValue::Blob display

* fix

* fix

* fix
  • Loading branch information
chenyan-dfinity authored Dec 12, 2023
1 parent e09e6c5 commit 2f6f90a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
16 changes: 12 additions & 4 deletions rust/candid/src/pretty/candid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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, "\"")
}
Expand All @@ -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!(),
}
Expand Down Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion rust/candid_parser/tests/parse_value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()),
Expand Down

0 comments on commit 2f6f90a

Please sign in to comment.