Skip to content

Commit a84f426

Browse files
committed
Update WriteBuf
1 parent 344cc3f commit a84f426

File tree

1 file changed

+11
-14
lines changed

1 file changed

+11
-14
lines changed

rts/motoko-rts/src/print.rs

+11-14
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@ macro_rules! format {
5858
})
5959
}
6060

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.
6163
pub(crate) struct WriteBuf<'a> {
6264
buf: &'a mut [u8],
6365
offset: usize,
@@ -76,23 +78,18 @@ impl<'a> WriteBuf<'a> {
7678
}
7779
}
7880

79-
// https://stackoverflow.com/questions/39488327/how-to-format-output-to-a-byte-array-with-no-std-and-no-allocator
8081
impl<'a> fmt::Write for WriteBuf<'a> {
8182
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.
8288
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;
9693
Ok(())
9794
}
9895
}

0 commit comments

Comments
 (0)