Debian Codegraph @

third_party/rust/zerovec-derive/examples/make.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 std::fmt::Debug;
6 use zerovec::*;
7
8 #[make_ule(StructULE)]
9 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
10 struct Struct {
11 a: u8,
12 b: u32,
13 c: Option<char>,
14 }
15
16 #[make_ule(HashedStructULE)]
17 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
18 #[zerovec::derive(Debug, Hash)]
19 struct HashedStruct {
20 a: u64,
21 b: i16,
22 c: Option<char>,
23 }
24
25 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
26 #[make_ule(TupleStructULE)]
27 struct TupleStruct(u8, char);
28
29 #[make_ule(EnumULE)]
30 #[repr(u8)]
31 #[derive(Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Debug)]
32 #[zerovec::derive(Debug, Hash)]
33 enum Enum {
34 A = 0,
35 B = 1,
36 D = 2,
37 E = 3,
38 FooBar = 4,
39 F = 5,
40 }
41
42 #[make_ule(OutOfOrderEnumULE)]
43 #[repr(u8)]
44 #[derive(Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Debug)]
45 #[allow(unused)]
46 enum OutOfOrderEnum {
47 A = 0,
48 B = 1,
49 E = 3,
50 FooBar = 4,
51 D = 2,
52 F = 5,
53 }
54
55 #[derive(Clone, Copy, Debug, PartialEq, Eq, Ord, PartialOrd)]
56 #[make_ule(NoKVULE)]
57 #[zerovec::skip_derive(ZeroMapKV)]
58 struct NoKV(u8, char);
59
60 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
61 #[make_ule(NoOrdULE)]
62 #[zerovec::skip_derive(ZeroMapKV, Ord)]
63 struct NoOrd(u8, char);
64
65 fn test_zerovec<T: ule::AsULE + Debug + PartialEq>(slice: &[T]) {
66 let zerovec: ZeroVec<T> = slice.iter().copied().collect();
67
68 assert_eq!(zerovec, slice);
69
70 let bytes = zerovec.as_bytes();
71 let name = std::any::type_name::<T>();
72 let reparsed: ZeroVec<T> = ZeroVec::parse_byte_slice(bytes)
73 .unwrap_or_else(|_| panic!("Parsing {name} should succeed"));
74
75 assert_eq!(reparsed, slice);
76 }
77
78 fn main() {
79 test_zerovec(TEST_SLICE_STRUCT);
80 test_zerovec(TEST_SLICE_TUPLESTRUCT);
81 test_zerovec(TEST_SLICE_ENUM);
82 }
83
84 const TEST_SLICE_STRUCT: &[Struct] = &[
85 Struct {
86 a: 101,
87 b: 924,
88 c: Some('⸘'),
89 },
90 Struct {
91 a: 217,
92 b: 4228,
93 c: Some('ə'),
94 },
95 Struct {
96 a: 117,
97 b: 9090,
98 c: Some('ø'),
99 },
100 ];
101
102 const TEST_SLICE_TUPLESTRUCT: &[TupleStruct] = &[
103 TupleStruct(101, 'ř'),
104 TupleStruct(76, '°'),
105 TupleStruct(15, 'a'),
106 ];
107
108 const TEST_SLICE_ENUM: &[Enum] = &[
109 Enum::A,
110 Enum::FooBar,
111 Enum::F,
112 Enum::D,
113 Enum::B,
114 Enum::FooBar,
115 Enum::E,
116 ];