Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_jdat/tests/derive.rs

7.9 KiB, 1 run

created by r1870400018:75869, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1use oxedyne_fe2o3_core::prelude::*;
2use oxedyne_fe2o3_jdat::prelude::*;
3
4use std::collections::BTreeMap;
5
6
7#[derive(Clone, Debug, PartialEq, ToDat, FromDat)]
8struct Unit;
9
10#[derive(Clone, Debug, PartialEq, ToDat, FromDat)]
11struct Pair(u32, String);
12
13#[derive(Clone, Debug, PartialEq, ToDat, FromDat)]
14struct Wrap(Vec<u8>);
15
16#[derive(Clone, Debug, PartialEq, ToDat, FromDat)]
17enum Shape {
18 Empty,
19 Point(i64, i64),
20 Named { label: String, size: Option<u16> },
21 One(Box<Shape>),
22}
23
24#[derive(Clone, Debug, PartialEq, ToDat, FromDat)]
25struct Change {
26 id: u64,
27 body: Shape,
28 bytes: Option<Vec<u8>>,
29 shapes: Option<Vec<Shape>>,
30 pairs: Vec<(String, u8)>,
31 triple: (bool, f64, i128),
32 quad: (u8, u16, u32, Pair),
33 index: BTreeMap<String, Vec<Shape>>,
34 flag: bool,
35 size: usize,
36 unit: Unit,
37 wrap: Wrap,
38 nothing: Option<String>,
39 outcome: Result<u32, String>,
40}
41
42#[derive(Clone, Debug, PartialEq, ToDat, FromDat)]
43struct Generic<T> {
44 item: T,
45 more: Vec<T>,
46}
47
48fn round<T: ToDat + FromDat + PartialEq + std::fmt::Debug>(v: &T) -> Outcome<()> {
49 let dat = res!(v.to_dat());
50 let back = res!(T::from_dat(dat.clone()));
51 assert_eq!(&back, v);
52 // And through the binary form.
53 let bytes = res!(dat.to_bytes(Vec::new()));
54 let (dat2, n) = res!(Dat::from_bytes(&bytes));
55 assert_eq!(n, bytes.len());
56 let back2 = res!(T::from_dat(dat2));
57 assert_eq!(&back2, v);
58 Ok(())
59}
60
61fn change() -> Change {
62 let mut index = BTreeMap::new();
63 index.insert("a".to_string(), vec![Shape::Empty, Shape::Point(-1, 2)]);
64 index.insert("b".to_string(), Vec::new());
65 Change {
66 id: 7,
67 body: Shape::Named { label: "x".to_string(), size: Some(3) },
68 bytes: Some(vec![0, 1, 255]),
69 shapes: Some(vec![Shape::Empty, Shape::One(Box::new(Shape::Point(1, 1)))]),
70 pairs: vec![("p".to_string(), 1), ("q".to_string(), 2)],
71 triple: (true, 2.5, -9),
72 quad: (1, 2, 3, Pair(4, "four".to_string())),
73 index,
74 flag: false,
75 size: usize::MAX,
76 unit: Unit,
77 wrap: Wrap(vec![9; 40]),
78 nothing: None,
79 outcome: Err("no".to_string()),
80 }
81}
82
83#[test]
84fn every_shape_round_trips() -> Outcome<()> {
85 res!(round(&Unit));
86 res!(round(&Pair(1, "one".to_string())));
87 res!(round(&Wrap(Vec::new())));
88 res!(round(&Shape::Empty));
89 res!(round(&Shape::Point(i64::MIN, i64::MAX)));
90 res!(round(&Shape::Named { label: String::new(), size: None }));
91 res!(round(&Shape::One(Box::new(Shape::Empty))));
92 res!(round(&change()));
93 res!(round(&Generic { item: 3u8, more: vec![4, 5] }));
94 res!(round(&Generic { item: Shape::Empty, more: vec![Shape::Point(0, 0)] }));
95 let nested: Option<Vec<Shape>> = Some(vec![Shape::Empty, Shape::Point(1, 2)]);
96 res!(round(&nested));
97 res!(round(&(1u8, "two".to_string())));
98 res!(round(&Ok::<u8, String>(3)));
99 Ok(())
100}
101
102#[test]
103fn the_encoding_is_the_documented_one() -> Outcome<()> {
104 // A unit variant is a one-entry map from its name to an empty daticle.
105 assert_eq!(res!(Shape::Empty.to_dat()), mapdat!{ "Empty" => Dat::Empty });
106 // A tuple variant maps to a list, a struct variant to a map of its fields.
107 assert_eq!(
108 res!(Shape::Point(1, 2).to_dat()),
109 mapdat!{ "Point" => listdat![1i64, 2i64] },
110 );
111 assert_eq!(
112 res!(Shape::Named { label: "l".to_string(), size: None }.to_dat()),
113 mapdat!{ "Named" => mapdat!{ "label" => "l", "size" => Dat::Opt(Box::new(None)) } },
114 );
115 // A named struct is a map, a tuple struct a list, a unit struct empty.
116 assert_eq!(res!(Pair(1, "a".to_string()).to_dat()), listdat![1u32, "a"]);
117 assert_eq!(res!(Unit.to_dat()), Dat::Empty);
118 // Bytes stay bytes.
119 assert_eq!(res!(vec![1u8, 2].to_dat()), Dat::BU64(vec![1, 2]));
120 Ok(())
121}
122
123#[test]
124fn an_unknown_variant_is_refused() -> Outcome<()> {
125 let dat = mapdat!{ "Hexagon" => Dat::Empty };
126 match Shape::from_dat(dat) {
127 Ok(v) => return Err(err!("Accepted {:?}.", v; Test)),
128 Err(e) => {
129 let s = e.plain();
130 assert!(s.contains("Shape") && s.contains("Hexagon"), "{}", s);
131 },
132 }
133 // Two entries are not one variant.
134 let dat = mapdat!{ "Empty" => Dat::Empty, "Point" => listdat![1i64, 2i64] };
135 assert!(Shape::from_dat(dat).is_err());
136 Ok(())
137}
138
139#[test]
140fn a_missing_field_is_refused() -> Outcome<()> {
141 let mut dat = res!(change().to_dat());
142 if let Dat::Map(map) = &mut dat {
143 map.remove(&dat!("body"));
144 }
145 match Change::from_dat(dat) {
146 Ok(v) => return Err(err!("Accepted {:?}.", v; Test)),
147 Err(e) => {
148 let s = e.plain();
149 assert!(s.contains("Change") && s.contains("body") && s.contains("Decoding"), "{}", s);
150 },
151 }
152 let dat = mapdat!{ "Named" => mapdat!{ "label" => "l" } };
153 match Shape::from_dat(dat) {
154 Ok(v) => return Err(err!("Accepted {:?}.", v; Test)),
155 Err(e) => {
156 let s = e.plain();
157 assert!(s.contains("Shape::Named") && s.contains("size"), "{}", s);
158 },
159 }
160 Ok(())
161}
162
163#[test]
164fn a_wrong_shape_is_refused() -> Outcome<()> {
165 // An unknown field, a short list, a nested fault named by its field.
166 let mut dat = res!(change().to_dat());
167 if let Dat::Map(map) = &mut dat {
168 map.insert(dat!("extra"), dat!(1u8));
169 }
170 assert!(Change::from_dat(dat).is_err());
171 assert!(Pair::from_dat(listdat![1u32]).is_err());
172 assert!(Pair::from_dat(listdat![1u32, "a", "b"]).is_err());
173 let mut dat = res!(change().to_dat());
174 if let Dat::Map(map) = &mut dat {
175 map.insert(dat!("body"), mapdat!{ "Point" => listdat![1i64] });
176 }
177 match Change::from_dat(dat) {
178 Ok(v) => return Err(err!("Accepted {:?}.", v; Test)),
179 Err(e) => {
180 let s = e.plain();
181 assert!(s.contains("body") && s.contains("Shape::Point"), "{}", s);
182 },
183 }
184 Ok(())
185}
186
187#[test]
188fn an_error_survives_the_trip() -> Outcome<()> {
189 let inner = err!("the inner fault"; Input, Missing);
190 let e: Error<ErrTag> = Error::Upstream(std::sync::Arc::new(inner), ErrMsg {
191 msg: "outer".to_string(),
192 tags: &[ErrTag::Wire],
193 });
194 let dat = res!(e.to_dat());
195 let bytes = res!(dat.to_bytes(Vec::new()));
196 let (dat2, _) = res!(Dat::from_bytes(&bytes));
197 let back = res!(Error::<ErrTag>::from_dat(dat2));
198 assert_eq!(back.tags(), e.tags());
199 assert_eq!(back.msgs(), e.msgs());
200 let r: Result<u8, Error<ErrTag>> = Err(e.clone());
201 let back = res!(Result::<u8, Error<ErrTag>>::from_dat(res!(r.to_dat())));
202 match back {
203 Err(b) => assert_eq!(b.tags(), e.tags()),
204 Ok(_) => return Err(err!("Lost the error."; Test)),
205 }
206 Ok(())
207}
208
209/// A module that glob-imports an enum whose variants are named `Ok`, `Err`, `Some` and `None`,
210/// so bare names in the generated code would resolve to these and not to the prelude's.
211mod glob {
212 use oxedyne_fe2o3_jdat::prelude::*;
213
214 #[derive(Clone, Debug, PartialEq, ToDat, FromDat)]
215 pub enum Reply {
216 Ok,
217 Err(String),
218 Some { n: u8 },
219 None,
220 }
221
222 pub use Reply::*;
223
224 #[derive(Clone, Debug, PartialEq, ToDat, FromDat)]
225 pub struct Held {
226 pub reply: Reply,
227 pub bytes: Vec<u8>,
228 pub pair: (u8, u16),
229 }
230
231 #[derive(Clone, Debug, PartialEq, ToDat, FromDat)]
232 pub struct Tup(pub Reply, pub u8);
233
234 #[derive(Clone, Debug, PartialEq, ToDat, FromDat)]
235 pub struct Nil;
236}
237
238#[test]
239fn a_glob_import_of_ok_and_err_does_not_break_the_derive() -> Outcome<()> {
240 use glob::{Held, Nil, Reply, Tup};
241 for r in [Reply::Ok, Reply::Err("no".to_string()), Reply::Some { n: 3 }, Reply::None] {
242 res!(round(&Held { reply: r.clone(), bytes: vec![1, 2], pair: (4, 5) }));
243 res!(round(&Tup(r, 9)));
244 }
245 res!(round(&Nil));
246 Ok(())
247}