pub trait FormatBuffer: AsRef<[u8]> {
// Required methods
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] ⓘ;
// Provided method
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)
where
F: FormatBuffer,
{
if offset_seconds >= 0 {
buf.write_char('+');
} else {
buf.write_char('-');
}
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§
Sourcefn write_fmt(&mut self, fmt: Arguments<'_>)
fn write_fmt(&mut self, fmt: Arguments<'_>)
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.
Sourcefn write_char(&mut self, c: char)
fn write_char(&mut self, c: char)
Writes a char into this buffer.
Provided Methods§
Dyn Compatibility§
This trait is dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".
Implementations on Foreign Types§
Source§impl FormatBuffer for BytesMut
Available on crate feature network only.
impl FormatBuffer for BytesMut
network only.