1use crate::{TinyAsciiStr, UnvalidatedTinyAsciiStr};
6use zerovec::maps::ZeroMapKV;
7use zerovec::ule::*;
8use zerovec::{ZeroSlice, ZeroVec};
9
10unsafe impl<const N: usize> ULE for TinyAsciiStr<N> {
20 #[inline]
21 fn validate_byte_slice(bytes: &[u8]) -> Result<(), ZeroVecError> {
22 if bytes.len() % N != 0 {
23 return Err(ZeroVecError::length::<Self>(bytes.len()));
24 }
25 for chunk in bytes.chunks_exact(N) {
27 let _ = TinyAsciiStr::<N>::from_bytes_inner(chunk, 0, N, true)
28 .map_err(|_| ZeroVecError::parse::<Self>())?;
29 }
30 Ok(())
31 }
32}
33
34impl<const N: usize> AsULE for TinyAsciiStr<N> {
35 type ULE = Self;
36
37 #[inline]
38 fn to_unaligned(self) -> Self::ULE {
39 self
40 }
41
42 #[inline]
43 fn from_unaligned(unaligned: Self::ULE) -> Self {
44 unaligned
45 }
46}
47
48impl<'a, const N: usize> ZeroMapKV<'a> for TinyAsciiStr<N> {
49 type Container = ZeroVec<'a, TinyAsciiStr<N>>;
50 type Slice = ZeroSlice<TinyAsciiStr<N>>;
51 type GetType = TinyAsciiStr<N>;
52 type OwnedType = TinyAsciiStr<N>;
53}
54
55unsafe impl<const N: usize> ULE for UnvalidatedTinyAsciiStr<N> {
65 #[inline]
66 fn validate_byte_slice(bytes: &[u8]) -> Result<(), ZeroVecError> {
67 if bytes.len() % N != 0 {
68 return Err(ZeroVecError::length::<Self>(bytes.len()));
69 }
70 Ok(())
71 }
72}
73
74impl<const N: usize> AsULE for UnvalidatedTinyAsciiStr<N> {
75 type ULE = Self;
76
77 #[inline]
78 fn to_unaligned(self) -> Self::ULE {
79 self
80 }
81
82 #[inline]
83 fn from_unaligned(unaligned: Self::ULE) -> Self {
84 unaligned
85 }
86}
87
88impl<'a, const N: usize> ZeroMapKV<'a> for UnvalidatedTinyAsciiStr<N> {
89 type Container = ZeroVec<'a, UnvalidatedTinyAsciiStr<N>>;
90 type Slice = ZeroSlice<UnvalidatedTinyAsciiStr<N>>;
91 type GetType = UnvalidatedTinyAsciiStr<N>;
92 type OwnedType = UnvalidatedTinyAsciiStr<N>;
93}
94
95#[cfg(test)]
96mod test {
97 use crate::*;
98 use zerovec::*;
99
100 #[test]
101 fn test_zerovec() {
102 let mut vec = ZeroVec::<TinyAsciiStr<7>>::new();
103
104 vec.with_mut(|v| v.push("foobar".parse().unwrap()));
105 vec.with_mut(|v| v.push("baz".parse().unwrap()));
106 vec.with_mut(|v| v.push("quux".parse().unwrap()));
107
108 let bytes = vec.as_bytes();
109
110 let vec: ZeroVec<TinyAsciiStr<7>> = ZeroVec::parse_byte_slice(bytes).unwrap();
111
112 assert_eq!(&*vec.get(0).unwrap(), "foobar");
113 assert_eq!(&*vec.get(1).unwrap(), "baz");
114 assert_eq!(&*vec.get(2).unwrap(), "quux");
115 }
116}