Skip to main content

zerovec/ule/
slices.rs

1// This file is part of ICU4X. For terms of use, please see the file
2// called LICENSE at the top level of the ICU4X source tree
3// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
4
5use crate::ule::*;
6
7// Safety (based on the safety checklist on the ULE trait):
8//  1. [T; N] does not include any uninitialized or padding bytes since T is ULE
9//  2. [T; N] is aligned to 1 byte since T is ULE
10//  3. The impl of validate_bytes() returns an error if any byte is not valid.
11//  4. The impl of validate_bytes() returns an error if there are leftover bytes.
12//  5. The other ULE methods use the default impl.
13//  6. [T; N] byte equality is semantic equality since T is ULE
14unsafe impl<T: ULE, const N: usize> ULE for [T; N] {
15    #[inline]
16    fn validate_bytes(bytes: &[u8]) -> Result<(), UleError> {
17        if N == 0 {
18            // ZSTs shouldn't be ULE
19            return Err(UleError::length::<Self>(bytes.len()));
20        }
21        if bytes.len() % size_of::<Self>() != 0 {
22            return Err(UleError::length::<Self>(bytes.len()));
23        }
24        // a slice of multiple Selfs is equivalent to just a larger slice of Ts
25        T::validate_bytes(bytes)
26    }
27}
28
29impl<T: AsULE, const N: usize> AsULE for [T; N] {
30    type ULE = [T::ULE; N];
31    #[inline]
32    fn to_unaligned(self) -> Self::ULE {
33        self.map(T::to_unaligned)
34    }
35    #[inline]
36    fn from_unaligned(unaligned: Self::ULE) -> Self {
37        unaligned.map(T::from_unaligned)
38    }
39}
40
41unsafe impl<T: EqULE, const N: usize> EqULE for [T; N] {}
42
43// Safety (based on the safety checklist on the VarULE trait):
44//  1. str does not include any uninitialized or padding bytes.
45//  2. str is aligned to 1 byte.
46//  3. The impl of `validate_bytes()` returns an error if any byte is not valid.
47//  4. The impl of `validate_bytes()` returns an error if the slice cannot be used in its entirety
48//  5. The impl of `from_bytes_unchecked()` returns a reference to the same data.
49//  6. `parse_bytes()` is equivalent to `validate_bytes()` followed by `from_bytes_unchecked()`
50//  7. str byte equality is semantic equality
51unsafe impl VarULE for str {
52    #[inline]
53    fn validate_bytes(bytes: &[u8]) -> Result<(), UleError> {
54        core::str::from_utf8(bytes).map_err(|_| UleError::parse::<Self>())?;
55        Ok(())
56    }
57
58    #[inline]
59    fn parse_bytes(bytes: &[u8]) -> Result<&Self, UleError> {
60        core::str::from_utf8(bytes).map_err(|_| UleError::parse::<Self>())
61    }
62    /// Invariant: must be safe to call when called on a slice that previously
63    /// succeeded with `parse_bytes`
64    #[inline]
65    unsafe fn from_bytes_unchecked(bytes: &[u8]) -> &Self {
66        core::str::from_utf8_unchecked(bytes)
67    }
68}
69
70/// Note: [`VarULE`] is well-defined for all `[T] where T: ULE`, but [`ZeroSlice`] is more ergonomic
71/// when `T` is a low-level ULE type. For example:
72///
73/// ```no_run
74/// # use zerovec::ZeroSlice;
75/// # use zerovec::VarZeroVec;
76/// # use zerovec::ule::AsULE;
77/// // OK: [u8] is a useful type
78/// let _: VarZeroVec<[u8]> = unimplemented!();
79///
80/// // Technically works, but [u32::ULE] is not very useful
81/// let _: VarZeroVec<[<u32 as AsULE>::ULE]> = unimplemented!();
82///
83/// // Better: ZeroSlice<u32>
84/// let _: VarZeroVec<ZeroSlice<u32>> = unimplemented!();
85/// ```
86///
87/// [`ZeroSlice`]: crate::ZeroSlice
88// Safety (based on the safety checklist on the VarULE trait):
89//  1. [T] does not include any uninitialized or padding bytes (achieved by being a slice of a ULE type)
90//  2. [T] is aligned to 1 byte (achieved by being a slice of a ULE type)
91//  3. The impl of `validate_bytes()` returns an error if any byte is not valid.
92//  4. The impl of `validate_bytes()` returns an error if the slice cannot be used in its entirety
93//  5. The impl of `from_bytes_unchecked()` returns a reference to the same data.
94//  6. All other methods are defaulted
95//  7. `[T]` byte equality is semantic equality (achieved by being a slice of a ULE type)
96unsafe impl<T> VarULE for [T]
97where
98    T: ULE,
99{
100    #[inline]
101    fn validate_bytes(slice: &[u8]) -> Result<(), UleError> {
102        T::validate_bytes(slice)
103    }
104
105    #[inline]
106    unsafe fn from_bytes_unchecked(bytes: &[u8]) -> &Self {
107        T::slice_from_bytes_unchecked(bytes)
108    }
109}
110
111#[cfg(test)]
112mod tests {
113    use super::*;
114    use crate::ZeroSlice;
115
116    #[test]
117    fn test_array_ule_validate() {
118        let bytes: &[u8] = &[1, 2, 3, 4, 5, 6];
119        assert!(<[u8; 2] as ULE>::validate_bytes(bytes).is_ok());
120        assert!(<[u8; 3] as ULE>::validate_bytes(bytes).is_ok());
121        assert!(<[u8; 6] as ULE>::validate_bytes(bytes).is_ok());
122
123        // Length not a multiple of array size
124        assert!(<[u8; 4] as ULE>::validate_bytes(bytes).is_err());
125        assert!(<[u8; 5] as ULE>::validate_bytes(bytes).is_err());
126        assert!(<[u8; 7] as ULE>::validate_bytes(bytes).is_err());
127
128        // Multi-byte element types (CharULE is 3 bytes, [CharULE; 2] is 6 bytes)
129        let chars_6b: &[u8] = &[0x61, 0x00, 0x00, 0x62, 0x00, 0x00]; // 'a', 'b'
130        assert!(<[CharULE; 2] as ULE>::validate_bytes(chars_6b).is_ok());
131        let chars_9b: &[u8] = &[0x61, 0x00, 0x00, 0x62, 0x00, 0x00, 0x63, 0x00, 0x00]; // 'a', 'b', 'c' (9 bytes: multiple of CharULE (3), but not [CharULE; 2] (6))
132        assert!(<[CharULE; 2] as ULE>::validate_bytes(chars_9b).is_err());
133
134        // ZeroSlice::parse_bytes
135        assert!(ZeroSlice::<[u8; 3]>::parse_bytes(bytes).is_ok());
136        assert!(ZeroSlice::<[u8; 4]>::parse_bytes(bytes).is_err());
137
138        // Zero-length arrays unconditionally error
139        assert!(<[u8; 0] as ULE>::validate_bytes(&[]).is_err());
140        assert!(<[u8; 0] as ULE>::validate_bytes(bytes).is_err());
141        assert!(ZeroSlice::<[u8; 0]>::parse_bytes(&[]).is_err());
142        assert!(ZeroSlice::<[u8; 0]>::parse_bytes(bytes).is_err());
143    }
144}