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 {
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.
220239pub struct BorrowedStr < ' a > ( & ' a str , #[ allow( unused) ] Lua ) ;
221240
Original file line number Diff line number Diff 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 _ => {
Original file line number Diff line number Diff 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\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