Skip to content

Commit

Permalink
impl: fix formatting of control characters \x1a through \x1f in Debug…
Browse files Browse the repository at this point in the history
… impl

Due to an incorrect range, control characters \x1a through \x1f get
formatted as Unicode \u escapes rather than hex \x escapes.

This commit fixes the range, adds a test and switches over to std's
`escape_ascii` to do more of the formatting work.

Without the fix, the test fails like this:

```
  left: "\"\\0\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x11\\x12\\r\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f \\x7f\\x80\\x81\\xfe\\xff\""
 right: "\"\\0\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x11\\x12\\r\\x14\\x15\\x16\\x17\\x18\\x19\\u{1a}\\u{1b}\\u{1c}\\u{1d}\\u{1e}\\u{1f} \\x7f\\x80\\x81\\xfe\\xff\""
```

PR #201
  • Loading branch information
joshtriplett authored Jan 2, 2025
1 parent 7cd4694 commit 732fc99
Showing 1 changed file with 9 additions and 12 deletions.
21 changes: 9 additions & 12 deletions src/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -525,6 +525,9 @@ mod bstr {
for (s, e, ch) in self.char_indices() {
match ch {
'\0' => write!(f, "\\0")?,
'\x01'..='\x7f' => {
write!(f, "{}", (ch as u8).escape_ascii())?;
}
'\u{FFFD}' => {
let bytes = self[s..e].as_bytes();
if bytes == b"\xEF\xBF\xBD" {
Expand All @@ -535,17 +538,6 @@ mod bstr {
}
}
}
// ASCII control characters except \0, \n, \r, \t
'\x01'..='\x08'
| '\x0b'
| '\x0c'
| '\x0e'..='\x19'
| '\x7f' => {
write!(f, "\\x{:02x}", ch as u32)?;
}
'\n' | '\r' | '\t' => {
write!(f, "{}", ch.escape_debug())?;
}
_ => {
write!(f, "{}", ch.escape_debug())?;
}
Expand Down Expand Up @@ -1305,7 +1297,12 @@ fn test_debug() {
// Before fixing #188, the output here would be:
// \\xED\\xA0\\x80Aa\\x7f\\x0b
B(&format!("{:?}", b"\xed\xa0\x80Aa\x7f\x0b".as_bstr())).as_bstr(),
)
);

assert_eq!(
r#""\0\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x11\x12\r\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f \x7f\x80\x81\xfe\xff""#,
format!("{:?}", b"\0\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x11\x12\r\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f \x7f\x80\x81\xfe\xff".as_bstr()),
);
}

// See: https://github.com/BurntSushi/bstr/issues/82
Expand Down

0 comments on commit 732fc99

Please sign in to comment.