@@ -58,6 +58,8 @@ macro_rules! format {
58
58
} )
59
59
}
60
60
61
+ /// A stack-allocated buffer that implements `core::fmt::Write`. `Write` methods will write to the
62
+ /// buffer until it's filled and then ignore the rest, without failing.
61
63
pub ( crate ) struct WriteBuf < ' a > {
62
64
buf : & ' a mut [ u8 ] ,
63
65
offset : usize ,
@@ -76,23 +78,18 @@ impl<'a> WriteBuf<'a> {
76
78
}
77
79
}
78
80
79
- // https://stackoverflow.com/questions/39488327/how-to-format-output-to-a-byte-array-with-no-std-and-no-allocator
80
81
impl < ' a > fmt:: Write for WriteBuf < ' a > {
81
82
fn write_str ( & mut self , s : & str ) -> fmt:: Result {
83
+ // Amount of space left in the write buffer
84
+ let buf_space_left = self . buf . len ( ) - self . offset ;
85
+ let buf = & mut self . buf [ self . offset ..] ;
86
+ // Copy the bytes to the buffer. Note that the buffer and the copied slice have to have the
87
+ // same length otherwise `copy_from_slice` panics.
82
88
let bytes = s. as_bytes ( ) ;
83
- // Skip over already-copied data
84
- let remainder = & mut self . buf [ self . offset ..] ;
85
- // Check if there is space remaining (return error instead of panicking)
86
- if remainder. len ( ) < bytes. len ( ) {
87
- return Err ( core:: fmt:: Error ) ;
88
- }
89
- // Make the two slices the same length
90
- let remainder = & mut remainder[ ..bytes. len ( ) ] ;
91
- // Copy
92
- remainder. copy_from_slice ( bytes) ;
93
- // Update offset to avoid overwriting
94
- self . offset += bytes. len ( ) ;
95
-
89
+ let copy_len = core:: cmp:: min ( buf_space_left, bytes. len ( ) ) ;
90
+ ( & mut buf[ ..copy_len] ) . copy_from_slice ( & bytes[ ..copy_len] ) ;
91
+ // Update offset
92
+ self . offset += copy_len;
96
93
Ok ( ( ) )
97
94
}
98
95
}
0 commit comments