Expand description
fmtbuf
This library is intended to help write formatted text to fixed buffers.
use fmtbuf::WriteBuf;
use std::fmt::Write;
let mut buf: [u8; 10] = [0; 10];
let mut writer = WriteBuf::new(&mut buf);
if let Err(e) = write!(&mut writer, "🚀🚀🚀") {
println!("write error: {e:?}");
}
let written_len = match writer.finish_with_or("!", "…") {
Ok(len) => len, // <- won't be hit since 🚀🚀🚀 is 12 bytes
Err(len) => {
println!("writing was truncated");
len
}
};
let written = &buf[..written_len];
assert_eq!("🚀…", std::str::from_utf8(written).unwrap());
A few things happened in that example:
- We stared with a 10 byte buffer
- Tried to write
"🚀🚀🚀"
to it, which is encoded as 3b"\xf0\x9f\x9a\x80"
s (12 bytes) - This can’t fit into 10 bytes, so only
"🚀🚀"
is stored and thewriter
is noted as having truncated writes - We finish the buffer with
"!"
on success or"…"
(a.k.a.b"\xe2\x80\xa6"
) on truncation - Since we noted truncation in step #3, we try to write
"…"
, but this can not fit into the buffer either, since 8 ("🚀🚀".len()
) + 3 ("…".len()
) > 12 (buf.len()
) - Roll the buffer back to the end of the first 🚀, then add …, leaving us with
"🚀…"
Structs
- A write buffer pointing to a
&mut [u8]
.
Functions
- Find the end of the last valid UTF-8 code point.