Debian Codegraph @

debian/rust-vendor/zerovec-derive/tests/derive_ule_test.rs

raw
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
5 use zerovec::ule::AsULE;
6 use zerovec::ule::UleError;
7 use zerovec::ule::ULE;
8 use zerovec::ZeroSlice;
9 use zerovec::ZeroVec;
10
11 #[derive(Debug, Copy, Clone)]
12 struct MyTuple(u16, char);
13
14 #[derive(ULE, Copy, Clone)]
15 #[repr(C, packed)]
16 struct MyTupleULE(<u16 as AsULE>::ULE, <char as AsULE>::ULE);
17
18 impl AsULE for MyTuple {
19 type ULE = MyTupleULE;
20 fn to_unaligned(self) -> Self::ULE {
21 MyTupleULE(self.0.to_unaligned(), self.1.to_unaligned())
22 }
23 fn from_unaligned(ule: Self::ULE) -> Self {
24 MyTuple(u16::from_unaligned(ule.0), char::from_unaligned(ule.1))
25 }
26 }
27
28 #[zerovec::make_ule(MyStructULE)]
29 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
30 struct MyStruct {
31 a: u16,
32 b: char,
33 }
34
35 #[test]
36 fn test_vec_validation() {
37 // Construct a valid ZeroVec<MyTuple>
38 let zv = ZeroVec::alloc_from_slice(&[MyTuple(1, 'a'), MyTuple(2, 'ß'), MyTuple(3, 'ç')]);
39 // Should succeed
40 ZeroSlice::<MyTuple>::parse_bytes(zv.as_bytes()).unwrap();
41
42 // Construct invalid bytes: 0xff are invalid bytes for char
43 let mut invalid_bytes = zv.as_bytes().to_vec();
44 // 0xff is invalid for char, which starts at index 7
45 invalid_bytes[7] = 0xff;
46 invalid_bytes[8] = 0xff;
47 invalid_bytes[9] = 0xff;
48 // Should fail
49 let err = ZeroSlice::<MyTuple>::parse_bytes(&invalid_bytes).unwrap_err();
50 assert!(matches!(err, UleError::ParseError { .. }));
51 }
52
53 #[test]
54 fn test_make_ule_vec_validation() {
55 // Construct a valid ZeroVec<MyStruct>
56 let zv = ZeroVec::alloc_from_slice(&[
57 MyStruct { a: 1, b: 'a' },
58 MyStruct { a: 2, b: 'ß' },
59 MyStruct { a: 3, b: 'ç' },
60 ]);
61 // Should succeed
62 ZeroSlice::<MyStruct>::parse_bytes(zv.as_bytes()).unwrap();
63
64 // Construct invalid bytes: 0xff are invalid bytes for char
65 let mut invalid_bytes = zv.as_bytes().to_vec();
66 // 0xff is invalid for char, which starts at index 7
67 invalid_bytes[7] = 0xff;
68 invalid_bytes[8] = 0xff;
69 invalid_bytes[9] = 0xff;
70 // Should fail
71 let err = ZeroSlice::<MyStruct>::parse_bytes(&invalid_bytes).unwrap_err();
72 assert!(matches!(err, UleError::ParseError { .. }));
73 }