1use crate::{TinyAsciiStr, UnvalidatedTinyAsciiStr};
6#[cfg(feature = "alloc")]
7use zerovec::maps::ZeroMapKV;
8use zerovec::ule::*;
9#[cfg(feature = "alloc")]
10use zerovec::{ZeroSlice, ZeroVec};
11
12unsafe impl<const N: usize> ULE for TinyAsciiStr<N> {
22    #[inline]
23    fn validate_bytes(bytes: &[u8]) -> Result<(), UleError> {
24        if bytes.len() % N != 0 {
25            return Err(UleError::length::<Self>(bytes.len()));
26        }
27        for chunk in bytes.chunks_exact(N) {
29            let _ = TinyAsciiStr::<N>::try_from_utf8_inner(chunk, true)
30                .map_err(|_| UleError::parse::<Self>())?;
31        }
32        Ok(())
33    }
34}
35
36impl<const N: usize> NicheBytes<N> for TinyAsciiStr<N> {
37    const NICHE_BIT_PATTERN: [u8; N] = [255; N];
39}
40
41impl<const N: usize> AsULE for TinyAsciiStr<N> {
42    type ULE = Self;
43
44    #[inline]
45    fn to_unaligned(self) -> Self::ULE {
46        self
47    }
48
49    #[inline]
50    fn from_unaligned(unaligned: Self::ULE) -> Self {
51        unaligned
52    }
53}
54
55#[cfg(feature = "alloc")]
56impl<'a, const N: usize> ZeroMapKV<'a> for TinyAsciiStr<N> {
57    type Container = ZeroVec<'a, TinyAsciiStr<N>>;
58    type Slice = ZeroSlice<TinyAsciiStr<N>>;
59    type GetType = TinyAsciiStr<N>;
60    type OwnedType = TinyAsciiStr<N>;
61}
62
63unsafe impl<const N: usize> ULE for UnvalidatedTinyAsciiStr<N> {
73    #[inline]
74    fn validate_bytes(bytes: &[u8]) -> Result<(), UleError> {
75        if bytes.len() % N != 0 {
76            return Err(UleError::length::<Self>(bytes.len()));
77        }
78        Ok(())
79    }
80}
81
82impl<const N: usize> AsULE for UnvalidatedTinyAsciiStr<N> {
83    type ULE = Self;
84
85    #[inline]
86    fn to_unaligned(self) -> Self::ULE {
87        self
88    }
89
90    #[inline]
91    fn from_unaligned(unaligned: Self::ULE) -> Self {
92        unaligned
93    }
94}
95
96#[cfg(feature = "alloc")]
97impl<'a, const N: usize> ZeroMapKV<'a> for UnvalidatedTinyAsciiStr<N> {
98    type Container = ZeroVec<'a, UnvalidatedTinyAsciiStr<N>>;
99    type Slice = ZeroSlice<UnvalidatedTinyAsciiStr<N>>;
100    type GetType = UnvalidatedTinyAsciiStr<N>;
101    type OwnedType = UnvalidatedTinyAsciiStr<N>;
102}
103
104#[cfg(test)]
105mod test {
106    use crate::*;
107    use zerovec::*;
108
109    #[test]
110    fn test_zerovec() {
111        let mut vec = ZeroVec::<TinyAsciiStr<7>>::new();
112
113        vec.with_mut(|v| v.push("foobar".parse().unwrap()));
114        vec.with_mut(|v| v.push("baz".parse().unwrap()));
115        vec.with_mut(|v| v.push("quux".parse().unwrap()));
116
117        let bytes = vec.as_bytes();
118
119        let vec: ZeroVec<TinyAsciiStr<7>> = ZeroVec::parse_bytes(bytes).unwrap();
120
121        assert_eq!(&*vec.get(0).unwrap(), "foobar");
122        assert_eq!(&*vec.get(1).unwrap(), "baz");
123        assert_eq!(&*vec.get(2).unwrap(), "quux");
124    }
125}