Skip to content

Commit 8c889cc

Browse files
committed
Add String::display method
1 parent 958abd0 commit 8c889cc

File tree

3 files changed

+34
-1
lines changed

3 files changed

+34
-1
lines changed

src/string.rs

+19
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,16 @@ impl String {
7878
StdString::from_utf8_lossy(&self.as_bytes()).into_owned()
7979
}
8080

81+
/// Returns an object that implements [`Display`] for safely printing a Lua [`String`] that may
82+
/// contain non-Unicode data.
83+
///
84+
/// This may perform lossy conversion.
85+
///
86+
/// [`Display`]: fmt::Display
87+
pub fn display(&self) -> impl fmt::Display + '_ {
88+
Display(self)
89+
}
90+
8191
/// Get the bytes that make up this string.
8292
///
8393
/// The returned slice will not contain the terminating nul byte, but will contain any nul
@@ -216,6 +226,15 @@ impl Serialize for String {
216226
}
217227
}
218228

229+
struct Display<'a>(&'a String);
230+
231+
impl fmt::Display for Display<'_> {
232+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
233+
let bytes = self.0.as_bytes();
234+
<bstr::BStr as fmt::Display>::fmt(bstr::BStr::new(&bytes), f)
235+
}
236+
}
237+
219238
/// A borrowed string (`&str`) that holds a strong reference to the Lua state.
220239
pub struct BorrowedStr<'a>(&'a str, #[allow(unused)] Lua);
221240

src/table.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -800,7 +800,7 @@ impl Table {
800800
for (key, value) in pairs {
801801
match key {
802802
Value::String(key) if is_simple_key(&key.as_bytes()) => {
803-
write!(fmt, "{}{}", " ".repeat(ident + 2), key.to_string_lossy())?;
803+
write!(fmt, "{}{}", " ".repeat(ident + 2), key.display())?;
804804
write!(fmt, " = ")?;
805805
}
806806
_ => {

tests/string.rs

+14
Original file line numberDiff line numberDiff line change
@@ -114,3 +114,17 @@ fn test_string_pointer() -> Result<()> {
114114

115115
Ok(())
116116
}
117+
118+
#[test]
119+
fn test_string_display() -> Result<()> {
120+
let lua = Lua::new();
121+
122+
let s = lua.create_string("hello")?;
123+
assert_eq!(format!("{}", s.display()), "hello");
124+
125+
// With invalid utf8
126+
let s = lua.create_string(b"hello\0world\xFF")?;
127+
assert_eq!(format!("{}", s.display()), "hello\0world�");
128+
129+
Ok(())
130+
}

0 commit comments

Comments
 (0)