Skip to main content

sciart_core/
text.rs

1//! Allocation-free text formatting for `render` (SPEC-001 CORE-R49, GEN-R11).
2//!
3//! `format!` allocates a `String`, which GEN-R11 forbids in `render`. [`StackText`] is a
4//! fixed-capacity buffer on the stack that implements [`core::fmt::Write`], so
5//! `write!(buf, "T/Tc {:.2}", t)` formats a readout with no heap traffic.
6
7use core::fmt;
8
9/// A fixed-capacity UTF-8 string of at most `N` bytes, living inline (CORE-R49).
10///
11/// Writes that do not fit are truncated silently on a char boundary, and once a write
12/// has been truncated every later write is dropped, so the contents are always a prefix
13/// of everything written. A HUD label that overflows loses its tail, never its validity.
14#[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    /// An empty buffer.
23    pub const fn new() -> Self {
24        Self {
25            buf: [0; N],
26            len: 0,
27            full: false,
28        }
29    }
30
31    /// The text written so far.
32    #[inline]
33    pub fn as_str(&self) -> &str {
34        // `write_str` only ever copies whole chars of a `&str`, so the prefix is valid
35        // UTF-8 and this never takes the fallback; it exists to stay panic- and
36        // `unsafe`-free.
37        core::str::from_utf8(&self.buf[..self.len]).unwrap_or("")
38    }
39
40    /// Length in bytes (`≤ N`).
41    #[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    /// Capacity in bytes.
52    #[inline]
53    pub const fn capacity(&self) -> usize {
54        N
55    }
56
57    /// Empty the buffer (and accept writes again after a truncation).
58    #[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    /// Append as much of `s` as fits, cut on a char boundary; always `Ok`, so a
73    /// truncated `write!` still formats (and drops) the remaining arguments quietly.
74    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            // `is_char_boundary(0)` is true, so this stops.
83            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/// A fixed-capacity UTF-8 string of at most `N` bytes that *errors* on overflow
112/// (CORE-R109): unlike [`StackText`] a write that does not fit returns [`fmt::Error`]
113/// and leaves the buffer unchanged, so a caller can fall back to a shorter form
114/// (`voyager_journey`'s readout fit ladder) instead of silently losing the tail.
115#[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    /// The text written so far (whole `&str` pieces only, so always valid UTF-8).
132    #[inline]
133    pub fn as_str(&self) -> &str {
134        core::str::from_utf8(&self.buf[..self.len]).unwrap_or("")
135    }
136
137    /// Bytes written so far (width-fitting decisions compare it against the canvas).
138    #[inline]
139    pub fn len(&self) -> usize {
140        self.len
141    }
142
143    /// Whether nothing has been written.
144    #[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}