#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CapacityError;
impl core::fmt::Display for CapacityError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("output exceeded the provided buffer capacity")
}
}
impl core::error::Error for CapacityError {}
#[derive(Debug)]
pub struct SliceWriter<'a> {
buf: &'a mut [u8],
len: usize,
}
impl<'a> SliceWriter<'a> {
pub fn new(buf: &'a mut [u8]) -> Self {
SliceWriter { buf, len: 0 }
}
pub fn len(&self) -> usize {
self.len
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
pub fn remaining(&self) -> usize {
self.buf.len() - self.len
}
pub fn as_str(&self) -> &str {
core::str::from_utf8(self.buf.get(..self.len).unwrap_or(&[])).unwrap_or("")
}
pub fn finish(self) -> &'a str {
let end = self.len.min(self.buf.len());
let (written, _) = self.buf.split_at(end);
core::str::from_utf8(written).unwrap_or("")
}
}
impl core::fmt::Write for SliceWriter<'_> {
fn write_str(&mut self, s: &str) -> core::fmt::Result {
let bytes = s.as_bytes();
let end = self.len.checked_add(bytes.len()).ok_or(core::fmt::Error)?;
let dst = self.buf.get_mut(self.len..end).ok_or(core::fmt::Error)?;
dst.copy_from_slice(bytes);
self.len = end;
Ok(())
}
}