From 83fbba5a4fdee5e62fd9933304a4da9d0b9051cb Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Fri, 1 Dec 2023 11:00:42 -0700 Subject: [PATCH] teach ValuePrinter about binary strings 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: https://github.com/wez/wezterm/pull/4336 --- luahelper/src/lib.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/luahelper/src/lib.rs b/luahelper/src/lib.rs index ade2c6bf3b9..3ff1216f507 100644 --- a/luahelper/src/lib.rs +++ b/luahelper/src/lib.rs @@ -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:#})"),