deep_time/ascii_str.rs
1use core::fmt::{self, Write};
2use core::str;
3
4/// Fixed-capacity, stack-only ASCII string stored in a single `[u8; N]` array.
5///
6/// The string is stored as raw bytes. Its logical length is determined at
7/// runtime by the position of the first nul byte (`b'\0'`). All bytes after
8/// the string content are guaranteed to be zero.
9#[derive(Clone, Copy, PartialEq, Eq)]
10pub struct AsciiStr<const N: usize> {
11 bytes: [u8; N],
12}
13
14impl<const N: usize> fmt::Debug for AsciiStr<N> {
15 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
16 match self.as_str() {
17 Ok(s) => write!(f, "{:?}", s),
18 Err(_) => write!(f, "AsciiStr(<invalid ascii>)"),
19 }
20 }
21}
22
23#[cfg(feature = "serde")]
24impl<const N: usize> serde::Serialize for AsciiStr<N> {
25 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
26 where
27 S: serde::Serializer,
28 {
29 self.as_str()
30 .map_err(serde::ser::Error::custom)?
31 .serialize(serializer)
32 }
33}
34
35#[cfg(feature = "serde")]
36impl<'de, const N: usize> serde::Deserialize<'de> for AsciiStr<N> {
37 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
38 where
39 D: serde::Deserializer<'de>,
40 {
41 let s: &str = serde::Deserialize::deserialize(deserializer)?;
42 AsciiStr::try_from_str(s).map_err(serde::de::Error::custom)
43 }
44}
45
46/// Errors returned by [`AsciiStr`] operations.
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum AsciiStrError {
49 /// Input contained non-ASCII characters.
50 InvalidAscii,
51 /// Input exceeded the fixed capacity `N`.
52 TooLong {
53 /// Maximum capacity of this `AsciiStr`.
54 capacity: usize,
55 /// Length of the rejected input.
56 length: usize,
57 },
58 /// Internal data is corrupted or violates the type invariant.
59 ///
60 /// This can occur when:
61 /// - The bytes are not valid UTF-8 (should never happen for ASCII data).
62 /// - Non-zero bytes appear after the first nul byte (violates the
63 /// "nul-terminated + trailing zeros" representation invariant).
64 ///
65 /// This variant exists only to keep the public API 100% panic-free.
66 /// It is unreachable when the type is constructed through the safe API.
67 CorruptedData,
68}
69
70// ─────────────────────────────────────────────────────────────────────────────
71// Display implementation (required by serde::ser::Error::custom / de::Error::custom)
72// ─────────────────────────────────────────────────────────────────────────────
73
74impl fmt::Display for AsciiStrError {
75 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76 match self {
77 AsciiStrError::InvalidAscii => f.write_str("input contained non-ASCII characters"),
78 AsciiStrError::TooLong { capacity, length } => {
79 write!(
80 f,
81 "input is too long: length {} exceeds capacity {}",
82 length, capacity
83 )
84 }
85 AsciiStrError::CorruptedData => {
86 f.write_str("internal data is corrupted or violates the representation invariant")
87 }
88 }
89 }
90}
91
92impl<const N: usize> AsciiStr<N> {
93 /// Creates a new empty `AsciiStr` (all bytes zero).
94 pub const fn new() -> Self {
95 Self { bytes: [0; N] }
96 }
97
98 /// Size of the wire representation in bytes (always equal to the capacity `N`).
99 pub const WIRE_SIZE: usize = N;
100
101 pub const DEFAULT: Self = Self::new();
102
103 /// Serializes this `AsciiStr` into a fixed-size byte array.
104 ///
105 /// The entire internal buffer is written (including trailing zeros after
106 /// the logical string content). This preserves the exact representation.
107 #[cfg(feature = "wire")]
108 #[inline]
109 pub fn to_wire_bytes(&self) -> [u8; N] {
110 self.bytes
111 }
112
113 /// Deserializes an `AsciiStr<N>` from exactly `N` bytes.
114 ///
115 /// The input must be valid ASCII. Any bytes after the first nul byte
116 /// must be zero (as required by the type invariant).
117 ///
118 /// Returns `None` if the input is not valid ASCII or violates the
119 /// internal representation rules.
120 #[cfg(feature = "wire")]
121 pub fn from_wire_bytes(bytes: &[u8]) -> Option<Self> {
122 if bytes.len() != N {
123 return None;
124 }
125 let mut arr = [0u8; N];
126 arr.copy_from_slice(bytes);
127 Self::try_from_filled_buffer(arr).ok()
128 }
129
130 /// Internal constructor used by the `strftime` formatter (and other
131 /// trusted code paths).
132 ///
133 /// The caller **must** guarantee that:
134 /// - The first `pos` bytes contain the formatted ASCII string.
135 /// - All remaining bytes are zero (nul-terminated).
136 ///
137 /// For untrusted input use the safe [`try_from_filled_buffer`](Self::try_from_filled_buffer) instead.
138 pub(crate) const fn from_filled_buffer(buffer: [u8; N]) -> Self {
139 Self { bytes: buffer }
140 }
141
142 /// Attempts to create an `AsciiStr<N>` from a raw byte buffer **safely**.
143 ///
144 /// This is the public, validated counterpart to the internal
145 /// [`from_filled_buffer`](Self::from_filled_buffer).
146 ///
147 /// It performs full validation:
148 /// - All bytes must be valid ASCII.
149 /// - Every byte after the first `b'\0'` must be zero (preserves the
150 /// nul-terminated + trailing-zeros invariant).
151 ///
152 /// Use this when you have untrusted or externally-supplied bytes
153 /// (network packets, C `strftime` output, user input, etc.).
154 ///
155 /// **This method (and the entire public API) is completely panic-free.**
156 /// All fallible operations return `Result` or `Option`.
157 ///
158 /// # Errors
159 /// - [`AsciiStrError::InvalidAscii`] if the buffer contains non-ASCII bytes.
160 /// - [`AsciiStrError::CorruptedData`] if bytes after the first nul are
161 /// not all zero (violates the representation invariant).
162 pub fn try_from_filled_buffer(buffer: [u8; N]) -> Result<Self, AsciiStrError> {
163 if !buffer.is_ascii() {
164 return Err(AsciiStrError::InvalidAscii);
165 }
166
167 if let Some(first_nul) = buffer.iter().position(|&b| b == 0) {
168 if buffer[first_nul..].iter().any(|&b| b != 0) {
169 return Err(AsciiStrError::CorruptedData);
170 }
171 }
172
173 Ok(Self { bytes: buffer })
174 }
175
176 /// Attempts to create an `AsciiStr<N>` from a string slice.
177 ///
178 /// # Errors
179 /// - [`AsciiStrError::InvalidAscii`] if the input is not ASCII.
180 /// - [`AsciiStrError::TooLong`] if the input exceeds capacity `N`.
181 pub fn try_from_str(s: &str) -> Result<Self, AsciiStrError> {
182 if !s.is_ascii() {
183 return Err(AsciiStrError::InvalidAscii);
184 }
185 if s.len() > N {
186 return Err(AsciiStrError::TooLong {
187 capacity: N,
188 length: s.len(),
189 });
190 }
191 let mut bytes = [0u8; N];
192 bytes[..s.len()].copy_from_slice(s.as_bytes());
193 Ok(Self { bytes })
194 }
195
196 /// Attempts to create an `AsciiStr<N>` from a string slice, **uppercasing** the input.
197 ///
198 /// This is a convenience wrapper around [`try_from_str`](Self::try_from_str)
199 /// that converts the input to ASCII uppercase before storing it.
200 ///
201 /// # Errors
202 /// - [`AsciiStrError::InvalidAscii`] if the input is not ASCII.
203 /// - [`AsciiStrError::TooLong`] if the input exceeds capacity `N`.
204 pub fn try_from_str_upper(s: &str) -> Result<Self, AsciiStrError> {
205 if !s.is_ascii() {
206 return Err(AsciiStrError::InvalidAscii);
207 }
208 if s.len() > N {
209 return Err(AsciiStrError::TooLong {
210 capacity: N,
211 length: s.len(),
212 });
213 }
214 let mut bytes = [0u8; N];
215 let src = s.as_bytes();
216 bytes[..src.len()].copy_from_slice(src);
217 bytes[..src.len()].make_ascii_uppercase();
218 Ok(Self { bytes })
219 }
220
221 /// Returns the stored string as `&str`.
222 ///
223 /// The length is computed by locating the first nul byte.
224 ///
225 /// # Errors
226 /// Returns [`AsciiStrError::CorruptedData`] only if the internal data
227 /// has become invalid UTF-8 (unreachable via safe constructors).
228 pub fn as_str(&self) -> Result<&str, AsciiStrError> {
229 let len = self
230 .bytes
231 .iter()
232 .position(|&b| b == 0)
233 .unwrap_or(self.bytes.len());
234 str::from_utf8(&self.bytes[..len]).map_err(|_| AsciiStrError::CorruptedData)
235 }
236
237 /// Returns the raw bytes of the stored string (excluding the trailing nul).
238 pub fn as_bytes(&self) -> &[u8] {
239 let len = self
240 .bytes
241 .iter()
242 .position(|&b| b == 0)
243 .unwrap_or(self.bytes.len());
244 &self.bytes[..len]
245 }
246
247 /// Returns the current logical length of the string.
248 pub fn len(&self) -> usize {
249 self.bytes
250 .iter()
251 .position(|&b| b == 0)
252 .unwrap_or(self.bytes.len())
253 }
254
255 /// Returns `true` if the string is empty.
256 pub const fn is_empty(&self) -> bool {
257 self.bytes[0] == 0
258 }
259
260 /// Returns the fixed maximum capacity of this type (always `N`).
261 pub const fn capacity(&self) -> usize {
262 N
263 }
264
265 /// Creates an `AsciiStr` from a `&str`, **truncating** if it exceeds capacity `N`.
266 ///
267 /// Non-ASCII characters are allowed.
268 pub fn from_str_truncate(s: &str) -> Self {
269 let mut bytes = [0u8; N];
270 let len = s.len().min(N);
271 bytes[..len].copy_from_slice(&s.as_bytes()[..len]);
272 Self { bytes }
273 }
274
275 /// Creates an `AsciiStr` from any type that implements `Display`.
276 /// The output is truncated if it exceeds capacity `N`.
277 ///
278 /// Very useful for embedding numbers, paths, etc. into errors.
279 pub fn from_display<T: core::fmt::Display>(value: T) -> Self {
280 let mut s = Self::new();
281 let _ = write!(&mut s, "{}", value);
282 s
283 }
284
285 /// Convenience: create from a format string (most ergonomic for errors)
286 pub fn from_fmt(args: core::fmt::Arguments<'_>) -> Self {
287 let mut s = Self::new();
288 let _ = write!(&mut s, "{}", args);
289 s
290 }
291}
292
293impl<const N: usize> TryFrom<&str> for AsciiStr<N> {
294 type Error = AsciiStrError;
295
296 fn try_from(s: &str) -> Result<Self, Self::Error> {
297 AsciiStr::try_from_str(s)
298 }
299}
300
301impl<const N: usize> TryFrom<[u8; N]> for AsciiStr<N> {
302 type Error = AsciiStrError;
303
304 /// Attempts to create an `AsciiStr<N>` from a filled buffer.
305 ///
306 /// This is the idiomatic, **completely panic-free** way to construct
307 /// from a byte array using the `?` operator or `.unwrap_or_else()`.
308 fn try_from(buffer: [u8; N]) -> Result<Self, Self::Error> {
309 AsciiStr::try_from_filled_buffer(buffer)
310 }
311}
312
313impl<const N: usize> core::fmt::Write for AsciiStr<N> {
314 fn write_str(&mut self, s: &str) -> core::fmt::Result {
315 if !s.is_ascii() {
316 return Err(core::fmt::Error);
317 }
318
319 let current_len = self.len();
320 let remaining = N.saturating_sub(current_len);
321
322 // Nothing space to write
323 if remaining == 0 {
324 return Ok(());
325 }
326
327 // Copy as much as possible (truncate if necessary)
328 let to_copy = s.len().min(remaining);
329
330 self.bytes[current_len..current_len + to_copy].copy_from_slice(&s.as_bytes()[..to_copy]);
331
332 Ok(())
333 }
334}