stackstring 0.4.4

A fixed-size string
Documentation
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
use core::{
    borrow::Borrow,
    cmp::{Eq, Ord, PartialEq, PartialOrd},
    convert::TryFrom,
    fmt,
    hash::{Hash, Hasher},
    ops::{self, Deref, DerefMut, Index, IndexMut},
    str,
};

use self::builder::StringBuilder;
use crate::error::Error;

pub mod builder;

#[cfg(feature = "rkyv-derive")]
mod rkyv;

#[cfg(feature = "serde-derive")]
pub mod serde;

/// A fixed-size inline string implementation, meant for simple use cases.
/// It doesn't keep any length; the assumption is that the capacity is always utilised
/// or space padding is accepted.
#[derive(Copy, Clone, Eq, PartialOrd, Ord)]
pub struct String<const L: usize>(pub(crate) [u8; L]);

impl<const L: usize> String<L> {
    pub const fn empty() -> Self {
        Self([b' '; L])
    }

    /// Constructs a `String<L>` from an _at most_ `L` bytes-long string slice,
    /// left-padding if the slice is less than `L` bytes-long.
    ///
    /// # Example
    ///
    /// ```
    /// # use stackstring::String;
    /// let s = "three";
    /// let string = String::<9>::try_from_str_padded(s).unwrap();
    ///
    /// assert_eq!(string, "three    ");
    ///
    /// let string_err = String::<3>::try_from_str_padded(s);
    ///
    /// assert!(string_err.is_err());
    /// ```
    pub fn try_from_str_padded(s: impl AsRef<str>) -> Result<Self, Error> {
        Self::try_from_bytes_padded(s.as_ref().as_bytes())
    }

    /// Constructs a `String<L>` from _at most_ `L` bytes.
    /// left-padding if the number of bytes is less than `L`.
    ///
    /// # Example
    ///
    /// ```
    /// # use stackstring::String;
    /// let bytes = b"three";
    /// let string = String::<9>::try_from_bytes_padded(bytes).unwrap();
    ///
    /// assert_eq!(string.as_bytes(), b"three    ");
    /// ```
    pub fn try_from_bytes_padded(bytes: impl AsRef<[u8]>) -> Result<Self, Error> {
        let bytes = bytes.as_ref();

        if bytes.len() > L {
            return Err(Error::new(L, bytes.len()));
        }

        let mut builder = Self::builder();
        unsafe {
            builder.push_bytes_unchecked(bytes);
        }

        Ok(builder.build())
    }

    pub const fn builder() -> StringBuilder<L> {
        StringBuilder::empty()
    }

    pub fn as_str(&self) -> &str {
        self
    }

    pub fn as_bytes(&self) -> &[u8; L] {
        &self.0
    }

    pub fn as_slice(&self) -> &[u8] {
        self.as_str().as_bytes()
    }

    /// Turns the `String` into its underlying bytes.
    pub fn into_bytes(self) -> [u8; L] {
        self.0
    }

    /// Returns whether all bytes in the `String` are empty.
    pub fn is_empty(&self) -> bool {
        self.0.iter().all(|&x| x == b' ')
    }

    /// Returns whether the first byte of the `String` is empty.
    /// Can be used as a faster version of `is_empty`.
    pub fn starts_empty(&self) -> bool {
        self.0[0] == b' '
    }
}

impl<const L: usize> String<L> {
    /// Creates a `String<L>` from another `String<K>`, provided that
    /// `K <= L` is satisfied.
    ///
    /// Will result in a compile error if `K > L`.
    ///
    /// # Warning
    ///
    /// The content of the new `String` in the range `[K..]` will be *blank-filled* (`' '`).
    ///
    /// # Example
    ///
    /// ```
    /// # fn main() {
    /// use stackstring::String;
    ///
    /// let s1 = String::<5>::from(b"abcde");
    /// let s2 = String::<10>::from_other(s1);
    ///
    /// assert_eq!(s2, "abcde     ");
    /// # }
    /// ```
    pub fn from_other<const K: usize>(other: impl Into<String<K>>) -> Self {
        const {
            assert!(
                K <= L,
                "String<L> can only be created from String<K> if K <= L"
            );
        }

        let mut buf = [b' '; L];
        buf[..K].copy_from_slice(other.into().as_bytes());
        String(buf)
    }

    /// Creates a `String<K>` from `self`, provided that
    /// `L <= K` is satisfied.
    ///
    /// Will result in a compile error if `L > K`.
    ///
    /// # Warning
    ///
    /// The content of the new `String` in the range `[L..]` will be *blank-filled* (`' '`).
    ///
    /// # Example
    ///
    /// ```
    /// # fn main() {
    /// use stackstring::String;
    ///
    /// let s1 = String::<5>::from(b"abcde");
    /// let s2 = s1.into_other::<10>();
    ///
    /// assert_eq!(s2, "abcde     ");
    /// # }
    /// ```
    pub fn into_other<const K: usize>(self) -> String<K> {
        String::<K>::from_other(self)
    }

    /// Creates a `String<K>` by trimming-down another `String<L>`,
    /// provided that `K < L` is satisfied.
    ///
    /// Will result in a compile error if `L <= K`.
    ///
    /// # Warning
    ///
    /// The content of the `String` in the range `[K..]` will be discarded.
    ///
    /// # Example
    ///
    /// ```
    /// # fn main() {
    /// use stackstring::String;
    ///
    /// let s1 = String::<5>::from(b"abcde");
    /// let s2 = s1.trim_down::<3>();
    ///
    /// assert_eq!(s2, "abc");
    /// # }
    /// ```
    pub fn trim_down<const K: usize>(self) -> String<K> {
        const {
            assert!(
                K < L,
                "String<L> can only be trimmed down to String<K> if K < L"
            );
        }

        let mut buf = [b' '; K];
        buf.copy_from_slice(&self.as_bytes()[..K]);
        String(buf)
    }
}

impl<const L: usize> Default for String<L> {
    fn default() -> Self {
        Self::empty()
    }
}

impl<const L: usize> fmt::Debug for String<L> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&**self, f)
    }
}

impl<const L: usize> fmt::Display for String<L> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&**self, f)
    }
}

impl<const L: usize> Deref for String<L> {
    type Target = str;

    fn deref(&self) -> &str {
        unsafe { core::str::from_utf8_unchecked(&self.0) }
    }
}

impl<const L: usize> DerefMut for String<L> {
    #[inline]
    fn deref_mut(&mut self) -> &mut str {
        unsafe { str::from_utf8_unchecked_mut(&mut self.0) }
    }
}

impl<const L: usize> AsRef<[u8]> for String<L> {
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl<const L: usize> AsRef<str> for String<L> {
    fn as_ref(&self) -> &str {
        self
    }
}

impl<const L: usize> From<[u8; L]> for String<L> {
    fn from(buf: [u8; L]) -> Self {
        String(buf)
    }
}

impl<const L: usize> From<&[u8; L]> for String<L> {
    fn from(buf: &[u8; L]) -> Self {
        String(*buf)
    }
}

impl<const L: usize> Hash for String<L> {
    #[inline]
    fn hash<H: Hasher>(&self, hasher: &mut H) {
        (**self).hash(hasher)
    }
}

impl<const L: usize> TryFrom<&str> for String<L> {
    type Error = crate::error::Error;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        if s.len() != L {
            return Err(Error::new(L, s.len()));
        }

        let mut res = Self::empty();

        res.0.copy_from_slice(s.as_bytes());

        Ok(res)
    }
}

impl<const L: usize> Borrow<str> for String<L> {
    #[inline]
    fn borrow(&self) -> &str {
        self
    }
}

impl<const L: usize> PartialEq for String<L> {
    #[inline]
    fn eq(&self, other: &String<L>) -> bool {
        PartialEq::eq(&self[..], &other[..])
    }
}

// == str eq ==
impl<const L: usize> PartialEq<str> for String<L> {
    #[inline]
    fn eq(&self, other: &str) -> bool {
        PartialEq::eq(&self[..], other)
    }
}

impl<const L: usize> PartialEq<&str> for String<L> {
    #[inline]
    fn eq(&self, other: &&str) -> bool {
        PartialEq::eq(&self[..], &other[..])
    }
}

impl<const L: usize> PartialEq<String<L>> for &str {
    #[inline]
    fn eq(&self, other: &String<L>) -> bool {
        PartialEq::eq(&self[..], &other[..])
    }
}

// == std String eq ==
impl<const L: usize> PartialEq<std::string::String> for String<L> {
    #[inline]
    fn eq(&self, other: &std::string::String) -> bool {
        PartialEq::eq(&self[..], &other[..])
    }
}

impl<const L: usize> PartialEq<String<L>> for std::string::String {
    #[inline]
    fn eq(&self, other: &String<L>) -> bool {
        PartialEq::eq(&self[..], &other[..])
    }
}

impl<const L: usize> ops::Index<ops::Range<usize>> for String<L> {
    type Output = str;

    #[inline]
    fn index(&self, index: ops::Range<usize>) -> &str {
        &self[..][index]
    }
}

impl<const L: usize> ops::Index<ops::RangeTo<usize>> for String<L> {
    type Output = str;

    #[inline]
    fn index(&self, index: ops::RangeTo<usize>) -> &str {
        &self[..][index]
    }
}

impl<const L: usize> ops::Index<ops::RangeFrom<usize>> for String<L> {
    type Output = str;

    #[inline]
    fn index(&self, index: ops::RangeFrom<usize>) -> &str {
        &self[..][index]
    }
}

impl<const L: usize> ops::Index<ops::RangeFull> for String<L> {
    type Output = str;

    #[inline]
    fn index(&self, _index: ops::RangeFull) -> &str {
        unsafe { str::from_utf8_unchecked(&self.0) }
    }
}

impl<const L: usize> ops::Index<ops::RangeInclusive<usize>> for String<L> {
    type Output = str;

    #[inline]
    fn index(&self, index: ops::RangeInclusive<usize>) -> &str {
        Index::index(&**self, index)
    }
}

impl<const L: usize> ops::Index<ops::RangeToInclusive<usize>> for String<L> {
    type Output = str;

    #[inline]
    fn index(&self, index: ops::RangeToInclusive<usize>) -> &str {
        Index::index(&**self, index)
    }
}

impl<const L: usize> ops::IndexMut<ops::Range<usize>> for String<L> {
    #[inline]
    fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str {
        &mut self[..][index]
    }
}

impl<const L: usize> ops::IndexMut<ops::RangeTo<usize>> for String<L> {
    #[inline]
    fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str {
        &mut self[..][index]
    }
}

impl<const L: usize> ops::IndexMut<ops::RangeFrom<usize>> for String<L> {
    #[inline]
    fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str {
        &mut self[..][index]
    }
}

impl<const L: usize> ops::IndexMut<ops::RangeFull> for String<L> {
    #[inline]
    fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str {
        unsafe { str::from_utf8_unchecked_mut(&mut self.0) }
    }
}

impl<const L: usize> ops::IndexMut<ops::RangeInclusive<usize>> for String<L> {
    #[inline]
    fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut str {
        IndexMut::index_mut(&mut **self, index)
    }
}

impl<const L: usize> ops::IndexMut<ops::RangeToInclusive<usize>> for String<L> {
    #[inline]
    fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut str {
        IndexMut::index_mut(&mut **self, index)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashSet;
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};

    #[test]
    fn deref() {
        let s_ = "abcde";
        let s = String::<5>::try_from(s_).unwrap();

        assert_eq!(s_, s);
    }

    #[test]
    fn slice() {
        let s = String::<3>::try_from("abc").unwrap();

        assert_eq!(&s[..2], "ab");
    }

    #[test]
    fn eq_impls() {
        let s_ = "abcde";
        let s = String::<5>::try_from(s_).unwrap();

        assert_eq!(s_, s);

        let s_ = s_.to_owned();
        assert_eq!(s_, s);
    }

    #[test]
    fn hash_set_contains() {
        let s_ = "abcde";
        let s = String::<5>::try_from(s_).unwrap();

        assert_eq!(<String<5> as Borrow<str>>::borrow(&s), s_);

        let mut hasher = DefaultHasher::new();
        s_.hash(&mut hasher);
        let s_hash = hasher.finish();
        let mut hasher = DefaultHasher::new();
        s.hash(&mut hasher);
        let ss_hash = hasher.finish();

        assert_eq!(s_hash, ss_hash);

        let set = HashSet::from([s]);

        assert!(set.contains(s_));

        let s_ = s_.to_owned();
        assert!(set.contains(s_.as_str()));
    }
}