pub struct FormatBuffer<const N: usize> { /* private fields */ }
Expand description
A self-contained buffer that can be used with both Rust’s formatting utilities and libc’s sprintf.
Because those tools panic on errors, overflowing writes are truncated rather
than returning an error. A non-zero truncation count is included in
Display
output of this object, and can be checked via the truncated
method.
The generic parameter N
is the internal size of the buffer. One byte is
reserved for NULL to support conversion to CStr
.
To format a message with Rust’s formatting:
use core::fmt::Write;
let mut buf = FormatBuffer::<1000>::new();
let x = 42;
write!(&mut buf, "{x}").unwrap();
assert_eq!(buf.as_str(), "42");
let y = 43;
write!(&mut buf, " {y}").unwrap();
assert_eq!(buf.as_str(), "42 43");
Implementations§
Source§impl<const N: usize> FormatBuffer<N>
impl<const N: usize> FormatBuffer<N>
pub fn new() -> Self
Sourcepub fn capacity_remaining(&self) -> usize
pub fn capacity_remaining(&self) -> usize
Remaining capacity in bytes.
pub fn capacity_remaining_including_null(&self) -> usize
Sourcepub fn truncated(&self) -> usize
pub fn truncated(&self) -> usize
How many bytes (not chars) have been truncated.
This shouldn’t be relied on for an exact count; in particular
the accounting is not precise in sprintf
if utf8 replacement
characters need to be inserted.
Sourcepub fn reset(&mut self)
pub fn reset(&mut self)
Reset to empty. This may be cheaper than assigning a fresh
FormatBuffer::new
, since the latter requires copying the uninitialized
buffer. (Though such a copy could get optimized to the same cost
depending on opt level, inlining, etc.)
Sourcepub fn as_str(&self) -> &str
pub fn as_str(&self) -> &str
str
representation of internal buffer.
If you’d like to render the buffer including any non-zero
truncation count, use the Display
attribute instead.
Sourcepub unsafe fn sprintf(&mut self, fmt: &CStr, args: VaList<'_>)
pub unsafe fn sprintf(&mut self, fmt: &CStr, args: VaList<'_>)
Appends the result of formatting fmt
and args
, following the conventions
of libc’s sprintf
.
Any non-utf8 sequences in the resulting string are replaced with the utf8 replacement character. If truncation occurs, the truncation count doesn’t necessarily account for all such substitutions.
Currently calls libc’s vsnprintf
internally and panics on unexpected error.
TODO: Ideally we’d find or create our own reimplementation of vsnprintf
instead,
since vsnprintf
isn’t guaranteed to be async-signal-safe.
§Safety
fmt
and args
must be consistent, as with arguments to libc’s sprintf
.