1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
//! Fixed-capacity ASCII string, allocated entirely on the stack.
//! Shared by the line discipline (`tty`) and the shell.
use core::fmt;
/// A fixed-capacity string allocated entirely on the stack.
pub struct String<const N: usize> {
buf: [u8; N],
len: usize,
}
impl<const N: usize> Default for String<N> {
fn default() -> Self {
Self::new()
}
}
impl<const N: usize> String<N> {
pub const fn new() -> Self {
String {
buf: [0u8; N],
len: 0,
}
}
pub fn as_str(&self) -> &str {
// SAFETY: we only write valid ASCII bytes.
unsafe { core::str::from_utf8_unchecked(&self.buf[..self.len]) }
}
pub fn push(&mut self, c: char) -> Result<(), ()> {
if self.len >= N {
return Err(());
}
self.buf[self.len] = c as u8;
self.len += 1;
Ok(())
}
pub fn pop(&mut self) -> Option<char> {
if self.len == 0 {
return None;
}
self.len -= 1;
Some(self.buf[self.len] as char)
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
pub fn clear(&mut self) {
self.len = 0;
}
pub fn trim(&self) -> &str {
self.as_str().trim()
}
}
impl<const N: usize> fmt::Display for String<N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}
impl<const N: usize> fmt::Debug for String<N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self.as_str())
}
}
|