use structio::{from_str, read_into, to_string};
#[derive(PartialEq, Debug)]
struct Reading {
id: u32,
}
structio::object!(Reading { id });
#[derive(PartialEq, Debug, Default)]
struct Body {
len: u32,
}
structio::object!(Body { len });
#[derive(PartialEq, Debug)]
enum Packet {
Data(Body),
Ack(u32),
}
structio::tagged_enum!(Packet { Data(_), Ack(_) });
#[test]
fn a_field_read_in_place_needs_no_default() {
let mut r = Reading { id: 0 };
read_into(&mut r, r#"{"id":7}"#).unwrap();
assert_eq!(r, Reading { id: 7 });
}
#[test]
fn a_tagged_enum_needs_no_default_of_its_own() {
assert_eq!(to_string(&Packet::Ack(3)), r#"{"Ack":3}"#);
let mut p = Packet::Data(Body { len: 0 });
read_into(&mut p, r#"{"Ack":9}"#).unwrap();
assert_eq!(p, Packet::Ack(9));
read_into(&mut p, r#"{"Data":{"len":4}}"#).unwrap();
assert_eq!(p, Packet::Data(Body { len: 4 }));
}
#[derive(PartialEq, Debug)]
struct Frame {
latest: Box<Reading>,
pair: [Reading; 2],
route: Box<Packet>,
}
structio::object!(Frame {
latest,
pair,
route
});
#[test]
fn box_and_fixed_array_hold_a_type_with_no_default() {
let mut f = Frame {
latest: Box::new(Reading { id: 0 }),
pair: [Reading { id: 0 }, Reading { id: 0 }],
route: Box::new(Packet::Ack(0)),
};
read_into(
&mut f,
r#"{"latest":{"id":1},"pair":[{"id":2},{"id":3}],"route":{"Data":{"len":5}}}"#,
)
.unwrap();
assert_eq!(*f.latest, Reading { id: 1 });
assert_eq!(f.pair, [Reading { id: 2 }, Reading { id: 3 }]);
assert_eq!(*f.route, Packet::Data(Body { len: 5 }));
}
#[derive(PartialEq, Debug, Default)]
struct Sample {
id: u32,
}
structio::object!(Sample { id });
#[derive(PartialEq, Debug, Default)]
struct Batch {
samples: Vec<Sample>,
}
structio::object!(Batch { samples });
#[test]
fn a_default_element_takes_the_growing_containers_and_from_str() {
let b: Batch = from_str(r#"{"samples":[{"id":1},{"id":2}]}"#).unwrap();
assert_eq!(b.samples, vec![Sample { id: 1 }, Sample { id: 2 }]);
}