Skip to main content

deep_time/
lite_str.rs

1use core::fmt;
2use core::str;
3
4/// A fixed-capacity, stack-allocated buffer that can hold a UTF-8 string.
5///
6/// `LiteStr<N>` stores its content in a `[u8; N]` array using C-style nul
7/// termination. The logical length is determined by the position of the first
8/// `b'\0'` byte (or `N` if the buffer is completely filled without a nul).
9///
10/// This type performs **no validation during construction**. UTF-8 validity is
11/// only checked when the content is accessed via [`as_str`], [`Debug`], or
12/// serialization.
13///
14/// Both [`new`] and [`from_bytes`] silently truncate input that exceeds the
15/// capacity `N`. This type is intentionally minimal because each `LiteStr<N>`
16/// is monomorphized independently.
17///
18/// ## .len()
19///
20/// - **Byte length**: Use [`as_bytes()`][Self::as_bytes]`.len()`
21/// - **Unicode character count**: Use `as_str().chars().count()`
22#[derive(Clone, Copy, PartialEq, Eq)]
23pub struct LiteStr<const N: usize> {
24    pub bytes: [u8; N],
25}
26
27impl<const N: usize> Default for LiteStr<N> {
28    #[inline(always)]
29    fn default() -> Self {
30        Self { bytes: [0; N] }
31    }
32}
33
34impl<const N: usize> LiteStr<N> {
35    pub const SIZE: usize = N;
36
37    /// Creates a new `LiteStr` from a `&str`.
38    ///
39    /// If the input is longer than `N` bytes, it is truncated at the nearest
40    /// valid UTF-8 boundary.
41    #[inline(always)]
42    pub fn new(s: &str) -> Self {
43        let mut bytes = [0u8; N];
44        copy_valid_utf8_prefix(&mut bytes, s.as_bytes(), N);
45        Self { bytes }
46    }
47
48    /// Returns the longest valid UTF-8 prefix of the content as a `&str`.
49    ///
50    /// - If the data is valid UTF-8, returns it directly.
51    /// - If the data starts with invalid bytes, returns a single replacement
52    ///   character (`�`).
53    /// - Otherwise returns only the valid prefix up to the first invalid
54    ///   sequence (everything after the first error is discarded).
55    ///
56    /// This method is infallible and never allocates.
57    #[inline(always)]
58    pub fn as_str(&self) -> &str {
59        let end = find_first_nul(&self.bytes);
60        let slice = &self.bytes[..end];
61
62        match str::from_utf8(slice) {
63            Ok(s) => s,
64            Err(e) => {
65                let valid = e.valid_up_to();
66                if valid == 0 {
67                    "\u{FFFD}" // first bytes are garbage → just show �
68                } else {
69                    // SAFETY: valid_up_to is always a valid UTF-8 boundary
70                    unsafe { str::from_utf8_unchecked(&slice[..valid]) }
71                }
72            }
73        }
74    }
75
76    /// Creates a `LiteStr<N>` from a byte slice.
77    ///
78    /// Copies up to `N` bytes from the input and zero-fills the remainder.
79    /// If `bytes.len() > N`, the input is silently truncated.
80    ///
81    /// No UTF-8 validation is performed.
82    #[inline(always)]
83    pub fn from_bytes(bytes: &[u8]) -> Self {
84        let mut arr = [0u8; N];
85        let len = bytes.len().min(N);
86        arr[..len].copy_from_slice(&bytes[..len]);
87        Self { bytes: arr }
88    }
89
90    /// Returns the content as a byte slice (up to the first nul byte).
91    #[inline(always)]
92    pub fn as_bytes(&self) -> &[u8] {
93        &self.bytes[..find_first_nul(&self.bytes)]
94    }
95}
96
97impl<const N: usize> fmt::Write for LiteStr<N> {
98    #[inline(never)]
99    fn write_str(&mut self, s: &str) -> fmt::Result {
100        let current = self.as_bytes().len();
101        let remaining = N.saturating_sub(current);
102        if remaining == 0 {
103            return Ok(());
104        }
105
106        copy_valid_utf8_prefix(&mut self.bytes[current..], s.as_bytes(), remaining);
107        Ok(())
108    }
109}
110
111impl<const N: usize> fmt::Display for LiteStr<N> {
112    #[inline(always)]
113    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114        f.write_str(self.as_str())
115    }
116}
117
118impl<const N: usize> fmt::Debug for LiteStr<N> {
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        write!(f, "{:?}", self.as_str())
121    }
122}
123
124#[cfg(feature = "serde")]
125impl<const N: usize> serde::Serialize for LiteStr<N> {
126    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
127    where
128        S: serde::Serializer,
129    {
130        self.as_str().serialize(serializer)
131    }
132}
133
134#[cfg(feature = "serde")]
135impl<'de, const N: usize> serde::Deserialize<'de> for LiteStr<N> {
136    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
137    where
138        D: serde::Deserializer<'de>,
139    {
140        let s: &str = serde::Deserialize::deserialize(deserializer)?;
141        Ok(LiteStr::new(s))
142    }
143}
144
145#[inline(never)]
146fn find_first_nul(bytes: &[u8]) -> usize {
147    bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len())
148}
149
150#[inline(never)]
151fn copy_valid_utf8_prefix(dst: &mut [u8], src: &[u8], max_len: usize) -> usize {
152    let len = src.len().min(max_len);
153    match str::from_utf8(&src[..len]) {
154        Ok(_) => {
155            dst[..len].copy_from_slice(&src[..len]);
156            len
157        }
158        Err(e) => {
159            let valid = e.valid_up_to();
160            dst[..valid].copy_from_slice(&src[..valid]);
161            valid
162        }
163    }
164}