@@ -19,11 +19,19 @@ impl<'a> WriteTo<'a> {
19
19
WriteTo { buffer, used : 0 }
20
20
}
21
21
22
- pub fn as_str ( self ) -> Option < & ' a str > {
22
+ pub fn into_str ( self ) -> Option < & ' a str > {
23
23
if self . used <= self . buffer . len ( ) {
24
24
// only successful concats of str - must be a valid str.
25
- use core:: str:: from_utf8_unchecked;
26
- Some ( unsafe { from_utf8_unchecked ( & self . buffer [ ..self . used ] ) } )
25
+ Some ( unsafe { core:: str:: from_utf8_unchecked ( & self . buffer [ ..self . used ] ) } )
26
+ } else {
27
+ None
28
+ }
29
+ }
30
+
31
+ pub fn into_cstr ( self ) -> Option < & ' a str > {
32
+ if self . used < self . buffer . len ( ) {
33
+ self . buffer [ self . used ] = 0 ; // Terminate the string
34
+ Some ( unsafe { core:: str:: from_utf8_unchecked ( & self . buffer [ ..=self . used ] ) } )
27
35
} else {
28
36
None
29
37
}
@@ -48,24 +56,46 @@ impl<'a> fmt::Write for WriteTo<'a> {
48
56
}
49
57
}
50
58
59
+ #[ inline]
51
60
pub fn show < ' a > ( buffer : & ' a mut [ u8 ] , args : fmt:: Arguments ) -> Result < & ' a str , fmt:: Error > {
52
61
let mut w = WriteTo :: new ( buffer) ;
53
62
fmt:: write ( & mut w, args) ?;
54
- w. as_str ( ) . ok_or ( fmt:: Error )
63
+ w. into_str ( ) . ok_or ( fmt:: Error )
64
+ }
65
+
66
+ // Return a zero-terminated str
67
+ #[ inline] // Crazy bug - result of this call disappears if it's not inlined
68
+ pub fn c_show < ' a > ( buffer : & ' a mut [ u8 ] , args : fmt:: Arguments ) -> Result < & ' a str , fmt:: Error > {
69
+ let mut w = WriteTo :: new ( buffer) ;
70
+ fmt:: write ( & mut w, args) ?;
71
+ w. into_cstr ( ) . ok_or ( fmt:: Error )
55
72
}
56
73
57
74
#[ cfg( test) ]
58
75
mod tests {
59
76
use super :: * ;
60
77
61
78
#[ test_case]
62
- pub fn write_to_functions ( ) {
79
+ pub fn write_to_works ( ) {
63
80
let mut buf = [ 0u8 ; 64 ] ;
64
81
let s: & str = show (
65
82
& mut buf,
66
83
format_args ! ( "write some stuff {:?}: {}" , "foo" , 42 ) ,
67
84
)
68
85
. unwrap ( ) ;
69
86
assert_eq ! ( s, "write some stuff \" foo\" : 42" ) ;
87
+ assert_eq ! ( s. as_ptr( ) , buf. as_ptr( ) ) ;
88
+ }
89
+
90
+ #[ test_case]
91
+ pub fn zero_terminated_write_to_works ( ) {
92
+ let mut buf = [ 0u8 ; 64 ] ;
93
+ let s: & str = c_show (
94
+ & mut buf,
95
+ format_args ! ( "write some stuff {:?}: {}" , "foo" , 42 ) ,
96
+ )
97
+ . unwrap ( ) ;
98
+ assert_eq ! ( s, "write some stuff \" foo\" : 42\0 " ) ;
99
+ assert_eq ! ( s. as_ptr( ) , buf. as_ptr( ) ) ;
70
100
}
71
101
}
0 commit comments