summaryrefslogtreecommitdiffstats
path: root/rsnix/src/strbuf.rs
blob: 0e3ea56e4d4f46c0a929764309b51b43a96bfcd0 (plain) (blame)
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
//! 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())
    }
}

/// Small `fmt::Write` over a byte slice — no allocation, bounded.
/// Shared by the panic handler (task-panic message) and the scheduler
/// (page-fault abort message) so they don't each reinvent it.
pub struct FmtBuf<'a> {
    b: &'a mut [u8],
    n: usize,
}

impl<'a> FmtBuf<'a> {
    pub fn new(b: &'a mut [u8]) -> Self {
        FmtBuf { b, n: 0 }
    }

    /// Bytes written so far (clamped at the buffer length).
    pub fn len(&self) -> usize {
        self.n
    }
}

impl fmt::Write for FmtBuf<'_> {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        let m = s.len().min(self.b.len() - self.n);
        self.b[self.n..self.n + m].copy_from_slice(&s.as_bytes()[..m]);
        self.n += m;
        Ok(())
    }
}