File tree Expand file tree Collapse file tree 3 files changed +34
-1
lines changed Expand file tree Collapse file tree 3 files changed +34
-1
lines changed Original file line number Diff line number Diff line change @@ -78,6 +78,16 @@ impl String {
78
78
StdString :: from_utf8_lossy ( & self . as_bytes ( ) ) . into_owned ( )
79
79
}
80
80
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
+
81
91
/// Get the bytes that make up this string.
82
92
///
83
93
/// The returned slice will not contain the terminating nul byte, but will contain any nul
@@ -216,6 +226,15 @@ impl Serialize for String {
216
226
}
217
227
}
218
228
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
+
219
238
/// A borrowed string (`&str`) that holds a strong reference to the Lua state.
220
239
pub struct BorrowedStr < ' a > ( & ' a str , #[ allow( unused) ] Lua ) ;
221
240
Original file line number Diff line number Diff line change @@ -800,7 +800,7 @@ impl Table {
800
800
for ( key, value) in pairs {
801
801
match key {
802
802
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 ( ) ) ?;
804
804
write ! ( fmt, " = " ) ?;
805
805
}
806
806
_ => {
Original file line number Diff line number Diff line change @@ -114,3 +114,17 @@ fn test_string_pointer() -> Result<()> {
114
114
115
115
Ok ( ( ) )
116
116
}
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\0 world\xFF " ) ?;
127
+ assert_eq ! ( format!( "{}" , s. display( ) ) , "hello\0 world�" ) ;
128
+
129
+ Ok ( ( ) )
130
+ }
You can’t perform that action at this time.
0 commit comments