summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAlex Orlenko <zxteam@protonmail.com>2024-11-09 14:24:43 +0000
committerAlex Orlenko <zxteam@protonmail.com>2024-11-09 14:24:43 +0000
commit8c889cc353ceb239850e90a0cc592ae4dd557425 (patch)
tree0cd4400c78ac29bae647e24b1ca3d6b46e6234ee
parent958abd050e629c5501c7f802bd890a3b0bdc42a6 (diff)
downloadmlua-8c889cc353ceb239850e90a0cc592ae4dd557425.zip
Add `String::display` method
-rw-r--r--src/string.rs19
-rw-r--r--src/table.rs2
-rw-r--r--tests/string.rs14
3 files changed, 34 insertions, 1 deletions
diff --git a/src/string.rs b/src/string.rs
index 04b7ee0..4424a8f 100644
--- a/src/string.rs
+++ b/src/string.rs
@@ -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
@@ -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);
diff --git a/src/table.rs b/src/table.rs
index ddf3ff3..eb12e96 100644
--- a/src/table.rs
+++ b/src/table.rs
@@ -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, " = ")?;
}
_ => {
diff --git a/tests/string.rs b/tests/string.rs
index 34a32de..7e2d877 100644
--- a/tests/string.rs
+++ b/tests/string.rs
@@ -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(())
+}