pub trait FormatBuffer: AsRef<[u8]> {
    fn write_fmt(&mut self, fmt: Arguments<'_>);
    fn write_char(&mut self, c: char);
    fn write_str(&mut self, s: &str);
    fn len(&self) -> usize;
    unsafe fn as_bytes_mut(&mut self) -> &mut [u8]Notable traits for &[u8]impl<'_> Read for &[u8]impl<'_> Write for &mut [u8];

    fn is_empty(&self) -> bool { ... }
Expand description

A trait for objects that can be infallibly written to.

Like std::fmt::Write, except that the methods do not return errors. Implementations are provided for String, bytes::BytesMut, and Vec<u8>, as writing to these types cannot fail.

Objects that implement FormatBuffer can be passed to the write! macro:

use mz_ore::fmt::FormatBuffer;

let mut buf = String::new();
write!(buf, "{:.02}", 1.0 / 7.0);
assert_eq!(buf, "0.14");

The trait is particularly useful for functions that need to generically write to either a String or a byte buffer:

use mz_ore::fmt::FormatBuffer;

fn write_timezone_offset<F>(buf: &mut F, mut offset_seconds: i32)
    F: FormatBuffer,
    if offset_seconds >= 0 {
    } else {
    let offset_seconds = offset_seconds.abs();
    write!(buf, "{:02}:{:02}", offset_seconds / 60 / 60, offset_seconds / 60 % 60);

let offset_seconds = -18000;

let mut s = String::new();
write_timezone_offset(&mut s, offset_seconds);

let mut v = Vec::new();
write_timezone_offset(&mut v, offset_seconds);

assert_eq!(s, "-05:00");
assert_eq!(v, s.as_bytes());

The implementations of FormatBuffer for Vec<u8> and BytesMut are guaranteed to only write valid UTF-8 bytes into the underlying buffer.

Required Methods

Glue for usage of the write! macro with implementors of this trait.

This method should not be invoked manually, but rather through the write! macro itself.

Writes a char into this buffer.

Writes a string into this buffer.

Returns the number of bytes in the buffer.

Returns a mutable reference to the bytes in the buffer.


If the byte slice was valid UTF-8, it must remain valid UTF-8 when the Strings or other data types whose memory safety depends upon only containing valid UTF-8.

Provided Methods

Reports whether the buffer is empty.

Implementations on Foreign Types