use core::fmt;
#[derive(Clone)]
pub struct StackText<const N: usize> {
buf: [u8; N],
len: usize,
full: bool,
}
impl<const N: usize> StackText<N> {
pub const fn new() -> Self {
Self {
buf: [0; N],
len: 0,
full: false,
}
}
#[inline]
pub fn as_str(&self) -> &str {
core::str::from_utf8(&self.buf[..self.len]).unwrap_or("")
}
#[inline]
pub fn len(&self) -> usize {
self.len
}
#[inline]
pub fn is_empty(&self) -> bool {
self.len == 0
}
#[inline]
pub const fn capacity(&self) -> usize {
N
}
#[inline]
pub fn clear(&mut self) {
self.len = 0;
self.full = false;
}
}
impl<const N: usize> Default for StackText<N> {
fn default() -> Self {
Self::new()
}
}
impl<const N: usize> fmt::Write for StackText<N> {
fn write_str(&mut self, s: &str) -> fmt::Result {
if self.full {
return Ok(());
}
let room = N - self.len;
let mut take = s.len().min(room);
if take < s.len() {
self.full = true;
while !s.is_char_boundary(take) {
take -= 1;
}
}
self.buf[self.len..self.len + take].copy_from_slice(&s.as_bytes()[..take]);
self.len += take;
Ok(())
}
}
impl<const N: usize> fmt::Display for StackText<N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl<const N: usize> fmt::Debug for StackText<N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self.as_str(), f)
}
}
impl<const N: usize> AsRef<str> for StackText<N> {
fn as_ref(&self) -> &str {
self.as_str()
}
}
#[derive(Clone, Debug)]
pub struct StackStr<const N: usize> {
buf: [u8; N],
len: usize,
}
impl<const N: usize> Default for StackStr<N> {
fn default() -> Self {
Self {
buf: [0; N],
len: 0,
}
}
}
impl<const N: usize> StackStr<N> {
#[inline]
pub fn as_str(&self) -> &str {
core::str::from_utf8(&self.buf[..self.len]).unwrap_or("")
}
#[inline]
pub fn len(&self) -> usize {
self.len
}
#[inline]
pub fn is_empty(&self) -> bool {
self.len == 0
}
}
impl<const N: usize> fmt::Write for StackStr<N> {
fn write_str(&mut self, s: &str) -> fmt::Result {
let end = self.len + s.len();
if end > self.buf.len() {
return Err(fmt::Error);
}
self.buf[self.len..end].copy_from_slice(s.as_bytes());
self.len = end;
Ok(())
}
}