Skip to content

Commit

Permalink
teach ValuePrinter about binary strings
Browse files Browse the repository at this point in the history
This commit changes how lua Strings are rendered when printing
them through ValuePrinter.

Previously, we'd try to convert to a utf8 string and print the bare
string to the output.  If it failed, we'd get a less than useful output;
for this example when inspecting the the `utf8` global module from
the debug overlay:

```
> utf8.charpattern
(error converting Lua string to &str (invalid utf-8 sequence of 1 bytes from index 4))
```

Now we handle the failure case and show it as a binary string using a
somewhat invented syntax; the `b"string"` syntax isn't valid in lua,
but it helps to communicate that this is a binary string:

```
> utf8.charpattern
b"[\x00-\x7f\xc2-\xfd][\x80-\xbf]*"
```

in addition, we now quote and escape unicode strings.

Previously;

```
> wezterm.target_triple
x86_64-unknown-linux-gnu
```

now:

```
> wezterm.target_triple
"x86_64-unknown-linux-gnu"
```

refs: #4336
  • Loading branch information
wez committed Dec 1, 2023
1 parent 9fc8dc0 commit 83fbba5
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions luahelper/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,23 @@ impl<'lua> std::fmt::Debug for ValuePrinterHelper<'lua> {
}
}
LuaValue::Error(e) => fmt.write_fmt(format_args!("error {}", e)),
LuaValue::String(s) => match s.to_str() {
Ok(s) => fmt.write_fmt(format_args!("\"{}\"", s.escape_default())),
Err(_) => {
let mut binary_string = "b\"".to_string();
for &b in s.as_bytes() {
if let Some(c) = char::from_u32(b as u32) {
if c.is_ascii_alphanumeric() || c.is_ascii_punctuation() || c == ' ' {
binary_string.push(c);
continue;
}
}
binary_string.push_str(&format!("\\x{b:02x}"));
}
binary_string.push('"');
fmt.write_str(&binary_string)
}
},
_ => match self.value.to_string() {
Ok(s) => fmt.write_str(&s),
Err(err) => write!(fmt, "({err:#})"),
Expand Down

0 comments on commit 83fbba5

Please sign in to comment.