Crate fmtbuf

Source
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:

  1. We stared with a 10 byte buffer
  2. Tried to write "πŸš€πŸš€πŸš€" to it, which is encoded as 3 b"\xf0\x9f\x9a\x80"s (12 bytes)
  3. This can’t fit into 10 bytes, so only "πŸš€πŸš€" is stored and the writer is noted as having truncated writes
  4. We finish the buffer with "!" on success or "…" (a.k.a. b"\xe2\x80\xa6") on truncation
  5. 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())
  6. Roll the buffer back to the end of the first πŸš€, then add …, leaving us with "πŸš€β€¦"

StructsΒ§

WriteBuf
A write buffer pointing to a &mut [u8].

FunctionsΒ§

rfind_utf8_end
Find the end of the last valid UTF-8 code point.