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 thewriteris 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Β§
- Write
Buf - A write buffer pointing to a
&mut [u8].
FunctionsΒ§
- rfind_
utf8_ end - Find the end of the last valid UTF-8 code point.