1use core::fmt;
8
9#[derive(Clone)]
15pub struct StackText<const N: usize> {
16 buf: [u8; N],
17 len: usize,
18 full: bool,
19}
20
21impl<const N: usize> StackText<N> {
22 pub const fn new() -> Self {
24 Self {
25 buf: [0; N],
26 len: 0,
27 full: false,
28 }
29 }
30
31 #[inline]
33 pub fn as_str(&self) -> &str {
34 core::str::from_utf8(&self.buf[..self.len]).unwrap_or("")
38 }
39
40 #[inline]
42 pub fn len(&self) -> usize {
43 self.len
44 }
45
46 #[inline]
47 pub fn is_empty(&self) -> bool {
48 self.len == 0
49 }
50
51 #[inline]
53 pub const fn capacity(&self) -> usize {
54 N
55 }
56
57 #[inline]
59 pub fn clear(&mut self) {
60 self.len = 0;
61 self.full = false;
62 }
63}
64
65impl<const N: usize> Default for StackText<N> {
66 fn default() -> Self {
67 Self::new()
68 }
69}
70
71impl<const N: usize> fmt::Write for StackText<N> {
72 fn write_str(&mut self, s: &str) -> fmt::Result {
75 if self.full {
76 return Ok(());
77 }
78 let room = N - self.len;
79 let mut take = s.len().min(room);
80 if take < s.len() {
81 self.full = true;
82 while !s.is_char_boundary(take) {
84 take -= 1;
85 }
86 }
87 self.buf[self.len..self.len + take].copy_from_slice(&s.as_bytes()[..take]);
88 self.len += take;
89 Ok(())
90 }
91}
92
93impl<const N: usize> fmt::Display for StackText<N> {
94 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95 f.write_str(self.as_str())
96 }
97}
98
99impl<const N: usize> fmt::Debug for StackText<N> {
100 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101 fmt::Debug::fmt(self.as_str(), f)
102 }
103}
104
105impl<const N: usize> AsRef<str> for StackText<N> {
106 fn as_ref(&self) -> &str {
107 self.as_str()
108 }
109}
110
111#[derive(Clone, Debug)]
116pub struct StackStr<const N: usize> {
117 buf: [u8; N],
118 len: usize,
119}
120
121impl<const N: usize> Default for StackStr<N> {
122 fn default() -> Self {
123 Self {
124 buf: [0; N],
125 len: 0,
126 }
127 }
128}
129
130impl<const N: usize> StackStr<N> {
131 #[inline]
133 pub fn as_str(&self) -> &str {
134 core::str::from_utf8(&self.buf[..self.len]).unwrap_or("")
135 }
136
137 #[inline]
139 pub fn len(&self) -> usize {
140 self.len
141 }
142
143 #[inline]
145 pub fn is_empty(&self) -> bool {
146 self.len == 0
147 }
148}
149
150impl<const N: usize> fmt::Write for StackStr<N> {
151 fn write_str(&mut self, s: &str) -> fmt::Result {
152 let end = self.len + s.len();
153 if end > self.buf.len() {
154 return Err(fmt::Error);
155 }
156 self.buf[self.len..end].copy_from_slice(s.as_bytes());
157 self.len = end;
158 Ok(())
159 }
160}