Skip to main content

kstring/
stack.rs

1#[cfg(not(feature = "std"))]
2use alloc::string::String;
3use core::fmt;
4
5pub(crate) type Len = u8;
6
7/// Fixed-size stack-allocated string
8#[derive(Copy, Clone)]
9#[deprecated(
10    since = "2.0.4",
11    note = "for alternatives, see https://github.com/rosetta-rs/string-rosetta-rs"
12)]
13pub struct StackString<const CAPACITY: usize> {
14    len: Len,
15    buffer: StrBuffer<CAPACITY>,
16}
17
18impl<const CAPACITY: usize> StackString<CAPACITY> {
19    pub const CAPACITY: usize = CAPACITY;
20    pub const EMPTY: Self = Self::empty();
21    const ASSERT_CAPACITY_FITS_IN_LEN: () =
22        assert!(CAPACITY <= Len::MAX as usize, "CAPACITY must be <= 255");
23
24    const fn empty() -> Self {
25        let () = Self::ASSERT_CAPACITY_FITS_IN_LEN;
26        Self {
27            len: 0,
28            buffer: StrBuffer::empty(),
29        }
30    }
31
32    /// Create a `StackString` from a `&str`, if it'll fit within `Self::CAPACITY`
33    ///
34    /// # Examples
35    ///
36    /// Basic usage:
37    ///
38    /// ```
39    /// let s = kstring::StackString::<3>::try_new("foo");
40    /// assert_eq!(s.as_deref(), Some("foo"));
41    /// let s = kstring::StackString::<3>::try_new("foobar");
42    /// assert_eq!(s, None);
43    /// ```
44    #[inline]
45    #[must_use]
46    pub fn try_new(s: &str) -> Option<Self> {
47        let () = Self::ASSERT_CAPACITY_FITS_IN_LEN;
48        let len = s.len();
49        if len <= Self::CAPACITY {
50            #[cfg(feature = "unsafe")]
51            let stack = {
52                unsafe {
53                    // SAFETY: We've confirmed `len` is within size
54                    Self::new_unchecked(s)
55                }
56            };
57            #[cfg(not(feature = "unsafe"))]
58            let stack = { Self::new(s) };
59            Some(stack)
60        } else {
61            None
62        }
63    }
64
65    /// Create a `StackString` from a `&str`
66    ///
67    /// # Panic
68    ///
69    /// Calling this function with a string larger than `Self::CAPACITY` will panic
70    ///
71    /// # Examples
72    ///
73    /// Basic usage:
74    ///
75    /// ```
76    /// let s = kstring::StackString::<3>::new("foo");
77    /// assert_eq!(s, "foo");
78    /// ```
79    #[inline]
80    #[must_use]
81    pub fn new(s: &str) -> Self {
82        let () = Self::ASSERT_CAPACITY_FITS_IN_LEN;
83        let buffer = StrBuffer::new(s);
84        let len = s.len() as u8; // guarded by `StrBuffer::new` assert
85        Self { len, buffer }
86    }
87
88    /// Create a `StackString` from a `&str`
89    ///
90    /// # Safety
91    ///
92    /// Calling this function with a string larger than `Self::CAPACITY` is undefined behavior.
93    ///
94    /// # Examples
95    ///
96    /// Basic usage:
97    ///
98    /// ```
99    /// let s = unsafe {
100    ///     // SAFETY: Literal is short-enough
101    ///     kstring::StackString::<3>::new_unchecked("foo")
102    /// };
103    /// assert_eq!(s, "foo");
104    /// ```
105    #[inline]
106    #[must_use]
107    #[cfg(feature = "unsafe")]
108    pub unsafe fn new_unchecked(s: &str) -> Self {
109        unsafe {
110            let () = Self::ASSERT_CAPACITY_FITS_IN_LEN;
111            let buffer = StrBuffer::new_unchecked(s);
112            let len = s.len() as u8; // covered by safety comment
113            Self { len, buffer }
114        }
115    }
116
117    /// Extracts a string slice containing the entire `StackString`.
118    ///
119    /// # Examples
120    ///
121    /// Basic usage:
122    ///
123    /// ```
124    /// let s = kstring::StackString::<3>::try_new("foo").unwrap();
125    ///
126    /// assert_eq!("foo", s.as_str());
127    /// ```
128    #[inline]
129    #[must_use]
130    pub fn as_str(&self) -> &str {
131        let len = self.len as usize;
132        #[cfg(feature = "unsafe")]
133        unsafe {
134            // SAFETY: Constructors guarantee that `buffer[..len]` is a `str`,
135            // and we don't mutate the data afterwards.
136            self.buffer.as_str_unchecked(len)
137        }
138        #[cfg(not(feature = "unsafe"))]
139        self.buffer.as_str(len)
140    }
141
142    /// Converts a `StackString` into a mutable string slice.
143    ///
144    /// # Examples
145    ///
146    /// Basic usage:
147    ///
148    /// ```
149    /// let mut s = kstring::StackString::<6>::try_new("foobar").unwrap();
150    /// let s_mut_str = s.as_mut_str();
151    ///
152    /// s_mut_str.make_ascii_uppercase();
153    ///
154    /// assert_eq!("FOOBAR", s_mut_str);
155    /// ```
156    #[inline]
157    #[must_use]
158    pub fn as_mut_str(&mut self) -> &mut str {
159        let len = self.len as usize;
160        #[cfg(feature = "unsafe")]
161        unsafe {
162            // SAFETY: Constructors guarantee that `buffer[..len]` is a `str`,
163            // and we don't mutate the data afterwards.
164            self.buffer.as_mut_str_unchecked(len)
165        }
166        #[cfg(not(feature = "unsafe"))]
167        self.buffer.as_mut_str(len)
168    }
169
170    /// Returns the length of this `StasckString`, in bytes, not [`char`]s or
171    /// graphemes. In other words, it might not be what a human considers the
172    /// length of the string.
173    ///
174    /// # Examples
175    ///
176    /// Basic usage:
177    ///
178    /// ```
179    /// let a = kstring::StackString::<3>::try_new("foo").unwrap();
180    /// assert_eq!(a.len(), 3);
181    ///
182    /// let fancy_f = kstring::StackString::<4>::try_new("ƒoo").unwrap();
183    /// assert_eq!(fancy_f.len(), 4);
184    /// assert_eq!(fancy_f.chars().count(), 3);
185    /// ```
186    #[inline]
187    #[must_use]
188    pub fn len(&self) -> usize {
189        self.len as usize
190    }
191
192    /// Returns `true` if this `StackString` has a length of zero, and `false` otherwise.
193    ///
194    /// # Examples
195    ///
196    /// Basic usage:
197    ///
198    /// ```
199    /// let mut v = kstring::StackString::<20>::EMPTY;
200    /// assert!(v.is_empty());
201    ///
202    /// let a = kstring::StackString::<3>::try_new("foo").unwrap();
203    /// assert!(!a.is_empty());
204    /// ```
205    #[inline]
206    #[must_use]
207    pub fn is_empty(&self) -> bool {
208        self.len() == 0
209    }
210
211    /// Truncates this `StackString`, removing all contents.
212    ///
213    /// # Examples
214    ///
215    /// Basic usage:
216    ///
217    /// ```
218    /// let mut s = kstring::StackString::<3>::try_new("foo").unwrap();
219    ///
220    /// s.clear();
221    ///
222    /// assert!(s.is_empty());
223    /// assert_eq!(0, s.len());
224    /// ```
225    #[inline]
226    pub fn clear(&mut self) {
227        self.len = 0;
228    }
229
230    /// Shortens this `StackString` to the specified length.
231    ///
232    /// If `new_len` is greater than the string's current length, this has no
233    /// effect.
234    ///
235    /// Note that this method has no effect on the allocated capacity
236    /// of the string
237    ///
238    /// # Panics
239    ///
240    /// Panics if `new_len` does not lie on a [`char`] boundary.
241    ///
242    /// # Examples
243    ///
244    /// Basic usage:
245    ///
246    /// ```
247    /// let mut s = kstring::StackString::<5>::try_new("hello").unwrap();
248    ///
249    /// s.truncate(2);
250    ///
251    /// assert_eq!(s, "he");
252    /// ```
253    #[inline]
254    pub fn truncate(&mut self, new_len: usize) {
255        if new_len <= self.len() {
256            assert!(self.is_char_boundary(new_len));
257            self.len = new_len as u8; // guardedd by `fn len()`
258        }
259    }
260}
261
262impl<const CAPACITY: usize> Default for StackString<CAPACITY> {
263    fn default() -> Self {
264        Self::empty()
265    }
266}
267
268impl<const CAPACITY: usize> core::ops::Deref for StackString<CAPACITY> {
269    type Target = str;
270
271    #[inline]
272    fn deref(&self) -> &str {
273        self.as_str()
274    }
275}
276
277impl<const CAPACITY: usize> Eq for StackString<CAPACITY> {}
278
279impl<const C1: usize, const C2: usize> PartialEq<StackString<C1>> for StackString<C2> {
280    #[inline]
281    fn eq(&self, other: &StackString<C1>) -> bool {
282        PartialEq::eq(self.as_str(), other.as_str())
283    }
284}
285
286impl<const CAPACITY: usize> PartialEq<str> for StackString<CAPACITY> {
287    #[inline]
288    fn eq(&self, other: &str) -> bool {
289        PartialEq::eq(self.as_str(), other)
290    }
291}
292
293impl<const CAPACITY: usize> PartialEq<&str> for StackString<CAPACITY> {
294    #[inline]
295    fn eq(&self, other: &&str) -> bool {
296        PartialEq::eq(self.as_str(), *other)
297    }
298}
299
300impl<const CAPACITY: usize> PartialEq<String> for StackString<CAPACITY> {
301    #[inline]
302    fn eq(&self, other: &String) -> bool {
303        PartialEq::eq(self.as_str(), other.as_str())
304    }
305}
306
307impl<const CAPACITY: usize> Ord for StackString<CAPACITY> {
308    #[inline]
309    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
310        self.as_str().cmp(other.as_str())
311    }
312}
313
314impl<const C1: usize, const C2: usize> PartialOrd<StackString<C1>> for StackString<C2> {
315    #[inline]
316    fn partial_cmp(&self, other: &StackString<C1>) -> Option<core::cmp::Ordering> {
317        self.as_str().partial_cmp(other.as_str())
318    }
319}
320
321impl<const CAPACITY: usize> PartialOrd<str> for StackString<CAPACITY> {
322    #[inline]
323    fn partial_cmp(&self, other: &str) -> Option<core::cmp::Ordering> {
324        self.as_str().partial_cmp(other)
325    }
326}
327
328impl<const CAPACITY: usize> PartialOrd<&str> for StackString<CAPACITY> {
329    #[inline]
330    fn partial_cmp(&self, other: &&str) -> Option<core::cmp::Ordering> {
331        self.as_str().partial_cmp(other)
332    }
333}
334
335impl<const CAPACITY: usize> PartialOrd<String> for StackString<CAPACITY> {
336    #[inline]
337    fn partial_cmp(&self, other: &String) -> Option<core::cmp::Ordering> {
338        self.as_str().partial_cmp(other.as_str())
339    }
340}
341
342impl<const CAPACITY: usize> core::hash::Hash for StackString<CAPACITY> {
343    #[inline]
344    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
345        self.as_str().hash(state);
346    }
347}
348
349impl<const CAPACITY: usize> fmt::Debug for StackString<CAPACITY> {
350    #[inline]
351    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
352        fmt::Debug::fmt(self.as_str(), f)
353    }
354}
355
356impl<const CAPACITY: usize> fmt::Display for StackString<CAPACITY> {
357    #[inline]
358    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
359        fmt::Display::fmt(self.as_str(), f)
360    }
361}
362
363impl<const CAPACITY: usize> AsRef<str> for StackString<CAPACITY> {
364    #[inline]
365    fn as_ref(&self) -> &str {
366        self.as_str()
367    }
368}
369
370impl<const CAPACITY: usize> AsRef<[u8]> for StackString<CAPACITY> {
371    #[inline]
372    fn as_ref(&self) -> &[u8] {
373        self.as_bytes()
374    }
375}
376
377#[cfg(feature = "std")]
378impl<const CAPACITY: usize> AsRef<std::ffi::OsStr> for StackString<CAPACITY> {
379    #[inline]
380    fn as_ref(&self) -> &std::ffi::OsStr {
381        (**self).as_ref()
382    }
383}
384
385#[cfg(feature = "std")]
386impl<const CAPACITY: usize> AsRef<std::path::Path> for StackString<CAPACITY> {
387    #[inline]
388    fn as_ref(&self) -> &std::path::Path {
389        std::path::Path::new(self)
390    }
391}
392
393impl<const CAPACITY: usize> alloc::borrow::Borrow<str> for StackString<CAPACITY> {
394    #[inline]
395    fn borrow(&self) -> &str {
396        self.as_str()
397    }
398}
399
400#[derive(Copy, Clone)]
401#[repr(transparent)]
402pub(crate) struct StrBuffer<const CAPACITY: usize>([u8; CAPACITY]);
403
404impl<const CAPACITY: usize> StrBuffer<CAPACITY> {
405    pub(crate) const fn empty() -> Self {
406        let array = [0; CAPACITY];
407        Self(array)
408    }
409
410    #[inline]
411    pub(crate) fn new(s: &str) -> Self {
412        let len = s.len();
413        debug_assert!(len <= CAPACITY);
414        let mut buffer = Self::default();
415        if let Some(buffer) = buffer.0.get_mut(..len) {
416            buffer.copy_from_slice(s.as_bytes());
417        } else {
418            panic!("`{s}` is larger than capacity {CAPACITY}");
419        }
420        buffer
421    }
422
423    #[inline]
424    #[cfg(not(feature = "unsafe"))]
425    pub(crate) fn as_str(&self, len: usize) -> &str {
426        let slice = self.0.get(..len).unwrap();
427        core::str::from_utf8(slice).unwrap()
428    }
429
430    #[inline]
431    #[cfg(not(feature = "unsafe"))]
432    pub(crate) fn as_mut_str(&mut self, len: usize) -> &mut str {
433        let slice = self.0.get_mut(..len).unwrap();
434        core::str::from_utf8_mut(slice).unwrap()
435    }
436}
437
438impl<const CAPACITY: usize> StrBuffer<CAPACITY> {
439    #[inline]
440    #[cfg(feature = "unsafe")]
441    pub(crate) unsafe fn new_unchecked(s: &str) -> Self {
442        unsafe {
443            let len = s.len();
444            debug_assert!(len <= CAPACITY);
445            let mut buffer = Self::default();
446            buffer
447                .0
448                .get_unchecked_mut(..len)
449                .copy_from_slice(s.as_bytes());
450            buffer
451        }
452    }
453
454    #[inline]
455    #[cfg(feature = "unsafe")]
456    pub(crate) unsafe fn as_str_unchecked(&self, len: usize) -> &str {
457        unsafe {
458            let slice = self.0.get_unchecked(..len);
459            core::str::from_utf8_unchecked(slice)
460        }
461    }
462
463    #[inline]
464    #[cfg(feature = "unsafe")]
465    pub(crate) unsafe fn as_mut_str_unchecked(&mut self, len: usize) -> &mut str {
466        unsafe {
467            let slice = self.0.get_unchecked_mut(..len);
468            core::str::from_utf8_unchecked_mut(slice)
469        }
470    }
471}
472
473impl<const CAPACITY: usize> Default for StrBuffer<CAPACITY> {
474    fn default() -> Self {
475        Self::empty()
476    }
477}