fmtbuf
Format into a fixed buffer.
Usage
use WriteBuf;
use Write;
ππ
The primary use case is for implementing APIs like strerror_r, where the
user provides the buffer.
use ;
use WriteBuf;
pub extern "C"
Why not write to &mut [u8]?
The Rust Standard Library trait std::io::Write is
implemented for &mut [u8]
which could be used instead of this library.
The problem with this approach is the lack of UTF-8 encoding support (also, it is not available in #![no_std]).
use ;
Running this program will show you the error:
write error: Error { kind: WriteZero, message: "failed to write whole buffer" }
wrote 10 bytes: [114, 111, 99, 107, 101, 116, 58, 32, 240, 159]
result: Err(Utf8Error { valid_up_to: 8, error_len: None })
The problem is that "rocket: π" is encoded as the 12 byte sequence -- the π emoji is encoded in UTF-8 as the 4 bytes
b"\xf0\x9f\x9a\x80" -- but our target buffer is only 10 bytes long.
The write! to the cursor naΓ―vely cuts off the π mid-encode, making the encoded string invalid UTF-8, even though it
advanced the cursor the entire 10 bytes.
This is expected, since std::io::Write comes from io and does not know anything about string encoding; it operates
on the u8 level.
One could use the std::str::Utf8Error to properly
cut off the buf.
The only issue with this is performance.
Since std::str::from_utf8 scans the whole string moving forward, it costs O(n) to test this, whereas fmtbuf will
do this in O(1), since it only looks at the final few bytes.