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
17 use flexbuffers::{BitWidth, Builder, Reader, ReaderError};
18
19
20 // In this Example we're creating a monster that corresponds to the following JSON:
21 // {
22 // "coins": [5, 10, 25, 25, 25, 100],
23 // "color": [255, 0, 0, 255],
24 // "enraged": true,
25 // "hp": 80,
26 // "mana": 200,
27 // "position": [0, 0, 0],
28 // "velocity": [1, 0, 0],
29 // "weapons": [
30 // "fist",
31 // {"damage": 15, "name": "great axe"},
32 // {"damage": 5, "name": "hammer"}]
33 // }
34 #[allow(clippy::float_cmp)]
main()35 fn main() {
36 // Create a new Flexbuffer builder.
37 let mut builder = Builder::default();
38
39 // The root of the builder can be a singleton, map or vector.
40 // Our monster will be represented with a map.
41 let mut monster = builder.start_map();
42
43 // Use `push` to add elements to a vector or map. Note that it up to the programmer to ensure
44 // duplicate keys are avoided and the key has no null bytes.
45 monster.push("hp", 80);
46 monster.push("mana", 200);
47 monster.push("enraged", true);
48
49 // Let's give our monster some weapons. Use `start_vector` to store a vector.
50 let mut weapons = monster.start_vector("weapons");
51
52 // The first weapon is a fist which has no damage so we'll store it as a string.
53 // Strings in Flexbuffers are utf8 encoded and are distinct from map Keys which are c strings.
54 weapons.push("fist");
55
56 // The monster also has an axe. We'll store it as a map to make it more interesting.
57 let mut axe = weapons.start_map();
58 axe.push("name", "great axe");
59 axe.push("damage", 15);
60 // We're done adding to the axe.
61 axe.end_map();
62
63 // The monster also has a hammer.
64 {
65 let mut hammer = weapons.start_map();
66 hammer.push("name", "hammer");
67 hammer.push("damage", 5);
68 // Instead of calling `hammer.end_map()`, we can just drop the `hammer` for the same effect.
69 // Vectors and maps are completed and serialized when their builders are dropped.
70 }
71
72 // We're done adding weapons.
73 weapons.end_vector();
74
75 // Give the monster some money. Flexbuffers has typed vectors which are smaller than
76 // heterogenous vectors. Elements of typed vectors can be pushed one at a time, as above, or
77 // they can be passed as a slice. This will be stored as a `FlexBufferType::VectorInt`.
78 monster.push("coins", &[5, 10, 25, 25, 25, 100]);
79
80 // Flexbuffer has special types for fixed-length-typed-vectors (if the length is 3 or 4 and the
81 // type is int, uint, or float). They're even more compact than typed vectors.
82 // The monster's position and Velocity will be stored as `FlexbufferType::VectorFloat3`.
83 monster.push("position", &[0.0; 3]);
84 monster.push("velocity", &[1.0, 0.0, 0.0]);
85
86 // Give the monster bright red skin. In rust, numbers are assumed integers until proven
87 // otherwise. We annotate u8 to tell flexbuffers to store it as a FlexbufferType::VectorUInt4.
88 monster.push("color", &[255, 0, 0, 255u8]);
89
90 // End the map at the root of the builder. This finishes the Flexbuffer.
91 monster.end_map();
92
93 // Now the buffer is free to be reused. Let's see the final buffer.
94 let data = builder.view();
95 println!("The monster was serialized in {:?} bytes.", data.len());
96
97 // Let's read and verify the data.
98 let root = Reader::get_root(data).unwrap();
99 println!("The monster: {}", root);
100
101 let read_monster = root.as_map();
102
103 // What attributes does this monster have?
104 let attrs: Vec<_> = read_monster.iter_keys().collect();
105 assert_eq!(
106 attrs,
107 vec!["coins", "color", "enraged", "hp", "mana", "position", "velocity", "weapons"]
108 );
109
110 // index into a vector or map with the `idx` method.
111 let read_hp = read_monster.idx("hp");
112 let read_mana = read_monster.idx("mana");
113 // If `idx` fails it will return a Null flexbuffer Reader
114
115 // Use `as_T` to cast the data to your desired type.
116 assert_eq!(read_hp.as_u8(), 80);
117 assert_eq!(read_hp.as_f32(), 80.0);
118 // If it fails it will return T::default().
119 assert_eq!(read_hp.as_str(), ""); // Its not a string.
120 assert_eq!(read_mana.as_i8(), 0); // 200 is not representable in i8.
121 assert!(read_mana.as_vector().is_empty()); // Its not a vector.
122 assert_eq!(read_monster.idx("foo").as_i32(), 0); // `foo` is not a monster attribute.
123
124 // To examine how your data is stored, check the flexbuffer type and bitwidth.
125 assert!(read_hp.flexbuffer_type().is_int());
126 assert!(read_mana.flexbuffer_type().is_int());
127 // Note that mana=200 is bigger than the maximum i8 so everything in the top layer of the
128 // monster map is stored in 16 bits.
129 assert_eq!(read_hp.bitwidth(), BitWidth::W16);
130 assert_eq!(read_monster.idx("mana").bitwidth(), BitWidth::W16);
131
132 // Use get_T functions if you want to ensure the flexbuffer type matches what you expect.
133 assert_eq!(read_hp.get_i64(), Ok(80));
134 assert!(read_hp.get_u64().is_err());
135 assert!(read_hp.get_vector().is_err());
136
137 // Analogously, the `index` method is the safe version of `idx`.
138 assert!(read_monster.index("hp").is_ok());
139 assert_eq!(
140 read_monster.index("foo").unwrap_err(),
141 ReaderError::KeyNotFound
142 );
143
144 // Maps can also be indexed by usize. They're stored by key so `coins` are the first element.
145 let monster_coins = read_monster.idx(0);
146 // Maps and Vectors can be iterated over.
147 assert!(monster_coins
148 .as_vector()
149 .iter()
150 .map(|r| r.as_u8())
151 .eq(vec![5, 10, 25, 25, 25, 100].into_iter()));
152
153 // Build the answer to life the universe and everything. Reusing a builder resets it. The
154 // reused internals won't need to reallocate leading to a potential 2x speedup.
155 builder.build_singleton(42);
156
157 // The monster is now no more.
158 assert_eq!(builder.view().len(), 3); // Bytes.
159
160 let the_answer = Reader::get_root(builder.view()).unwrap();
161 assert_eq!(the_answer.as_i32(), 42);
162 }
163
164 #[test]
test_main()165 fn test_main() {
166 main()
167 }
168