pub struct WriteBuf<'a> { /* private fields */ }Expand description
A write buffer pointing to a &mut [u8].
use fmtbuf::WriteBuf;
use std::fmt::Write;
// The buffer to write into. The contents can be uninitialized, but using a
// bogus `\xff` sigil for demonstration.
let mut buf: [u8; 128] = [0xff; 128];
let mut writer = WriteBuf::new(&mut buf);
// Write data to the buffer.
write!(writer, "some data: {}", 0x01a4).unwrap();
// Finish writing:
let write_len = writer.finish().unwrap();
let written = std::str::from_utf8(&buf[..write_len]).unwrap();
assert_eq!(written, "some data: 420");Implementations§
source§impl<'a> WriteBuf<'a>
impl<'a> WriteBuf<'a>
sourcepub fn new(target: &'a mut [u8]) -> Self
pub fn new(target: &'a mut [u8]) -> Self
Create an instance that will write to the given target. The contents of the target do not need to have been
initialized before this, as they will be overwritten by writing.
sourcepub fn position(&self) -> usize
pub fn position(&self) -> usize
Get the position in the target buffer. The value is one past the end of written content and the next position to be written to.
sourcepub fn finish(self) -> Result<usize, usize>
pub fn finish(self) -> Result<usize, usize>
Returns
In both the Ok and Err cases, the WriteBuf::position is returned. The Ok case indicates the truncation
did not occur, while Err indicates that it did.
sourcepub fn finish_with(self, suffix: &[u8]) -> Result<usize, usize>
pub fn finish_with(self, suffix: &[u8]) -> Result<usize, usize>
Finish the buffer, adding the suffix to the end. A common use case for this is to add a null terminator.
This operates slightly differently than the normal format writing function write_str in that the suffix is
always put at the end. The only case where this will not happen is when suffix.len() is less than the size of
the buffer originally provided. In this case, the last bit of suffix will be copied.
use fmtbuf::WriteBuf;
let mut buf: [u8; 4] = [0xff; 4];
let mut writer = WriteBuf::new(&mut buf);
// Finish writing with too many bytes:
let write_len = writer.finish_with(b"12345").unwrap_err();
assert_eq!(write_len, 4);
let buf_str = std::str::from_utf8(&buf).unwrap();
assert_eq!(buf_str, "2345");Returns
The returned value has the same meaning as WriteBuf::finish.