Skip to content

Commit

Permalink
Add String::display method
Browse files Browse the repository at this point in the history
  • Loading branch information
khvzak committed Nov 9, 2024
1 parent 958abd0 commit 8c889cc
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
19 changes: 19 additions & 0 deletions src/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,16 @@ impl String {
StdString::from_utf8_lossy(&self.as_bytes()).into_owned()
}

/// Returns an object that implements [`Display`] for safely printing a Lua [`String`] that may
/// contain non-Unicode data.
///
/// This may perform lossy conversion.
///
/// [`Display`]: fmt::Display
pub fn display(&self) -> impl fmt::Display + '_ {
Display(self)
}

/// Get the bytes that make up this string.
///
/// The returned slice will not contain the terminating nul byte, but will contain any nul
Expand Down Expand Up @@ -216,6 +226,15 @@ impl Serialize for String {
}
}

struct Display<'a>(&'a String);

impl fmt::Display for Display<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let bytes = self.0.as_bytes();
<bstr::BStr as fmt::Display>::fmt(bstr::BStr::new(&bytes), f)
}
}

/// A borrowed string (`&str`) that holds a strong reference to the Lua state.
pub struct BorrowedStr<'a>(&'a str, #[allow(unused)] Lua);

Expand Down
2 changes: 1 addition & 1 deletion src/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -800,7 +800,7 @@ impl Table {
for (key, value) in pairs {
match key {
Value::String(key) if is_simple_key(&key.as_bytes()) => {
write!(fmt, "{}{}", " ".repeat(ident + 2), key.to_string_lossy())?;
write!(fmt, "{}{}", " ".repeat(ident + 2), key.display())?;
write!(fmt, " = ")?;
}
_ => {
Expand Down
14 changes: 14 additions & 0 deletions tests/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,3 +114,17 @@ fn test_string_pointer() -> Result<()> {

Ok(())
}

#[test]
fn test_string_display() -> Result<()> {
let lua = Lua::new();

let s = lua.create_string("hello")?;
assert_eq!(format!("{}", s.display()), "hello");

// With invalid utf8
let s = lua.create_string(b"hello\0world\xFF")?;
assert_eq!(format!("{}", s.display()), "hello\0world�");

Ok(())
}

0 comments on commit 8c889cc

Please sign in to comment.