1 // Copyright 2019 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 extern crate flexbuffers;
16 extern crate serde;
17 #[macro_use]
18 extern crate serde_derive;
19 use serde::{Deserialize, Serialize};
20
21 #[derive(Debug, PartialEq, Serialize, Deserialize)]
22 enum Weapon {
23 Fist,
24 Equipment { name: String, damage: i32 },
25 }
26
27 #[derive(Debug, PartialEq, Serialize, Deserialize)]
28 struct Color(u8, u8, u8, u8);
29
30 #[derive(Debug, PartialEq, Serialize, Deserialize)]
31 struct Monster {
32 hp: u32,
33 mana: i32,
34 enraged: bool,
35 weapons: Vec<Weapon>,
36 color: Color,
37 position: [f64; 3],
38 velocity: [f64; 3],
39 coins: Vec<u32>,
40 }
41
main()42 fn main() {
43 let monster = Monster {
44 hp: 80,
45 mana: 200,
46 enraged: true,
47 color: Color(255, 255, 255, 255),
48 position: [0.0; 3],
49 velocity: [1.0, 0.0, 0.0],
50 weapons: vec![
51 Weapon::Fist,
52 Weapon::Equipment {
53 name: "great axe".to_string(),
54 damage: 15,
55 },
56 Weapon::Equipment {
57 name: "hammer".to_string(),
58 damage: 5,
59 },
60 ],
61 coins: vec![5, 10, 25, 25, 25, 100],
62 };
63 let mut s = flexbuffers::FlexbufferSerializer::new();
64 monster.serialize(&mut s).unwrap();
65
66 let r = flexbuffers::Reader::get_root(s.view()).unwrap();
67
68 // Serialization is similar to JSON. Field names are stored in the buffer but are reused
69 // between all maps and structs.
70 println!("Monster stored in {:?} bytes.", s.view().len());
71 println!("{}", r);
72
73 let monster2 = Monster::deserialize(r).unwrap();
74
75 assert_eq!(monster, monster2);
76 }
77
78 #[test]
test_main()79 fn test_main() {
80 main()
81 }
82