• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2018 Google Inc. All rights reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 // import the flatbuffers runtime library
18 extern crate flatbuffers;
19 
20 // import the generated code
21 #[allow(dead_code, unused_imports)]
22 #[path = "./monster_generated.rs"]
23 #[allow(clippy::approx_constant)]  // We use low precision PI as a default value.
24 mod monster_generated;
25 pub use monster_generated::my_game::sample::{Color, Equipment,
26                                              Monster, MonsterArgs,
27                                              Vec3,
28                                              Weapon, WeaponArgs};
29 
30 
31 // Example how to use FlatBuffers to create and read binary buffers.
32 #[allow(clippy::float_cmp)]
main()33 fn main() {
34   // Build up a serialized buffer algorithmically.
35   // Initialize it with a capacity of 1024 bytes.
36   let mut builder = flatbuffers::FlatBufferBuilder::new_with_capacity(1024);
37 
38   // Serialize some weapons for the Monster: A 'sword' and an 'axe'.
39   let weapon_one_name = builder.create_string("Sword");
40   let weapon_two_name = builder.create_string("Axe");
41 
42   // Use the `Weapon::create` shortcut to create Weapons with named field
43   // arguments.
44   let sword = Weapon::create(&mut builder, &WeaponArgs{
45       name: Some(weapon_one_name),
46       damage: 3,
47   });
48   let axe = Weapon::create(&mut builder, &WeaponArgs{
49       name: Some(weapon_two_name),
50       damage: 5,
51   });
52 
53   // Name of the Monster.
54   let name = builder.create_string("Orc");
55 
56   // Inventory.
57   let inventory = builder.create_vector(&[0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
58 
59   // Create a FlatBuffer `vector` that contains offsets to the sword and axe
60   // we created above.
61   let weapons = builder.create_vector(&[sword, axe]);
62 
63   // Create the path vector of Vec3 objects:
64   //let x = Vec3::new(1.0, 2.0, 3.0);
65   //let y = Vec3::new(4.0, 5.0, 6.0);
66   //let path = builder.create_vector(&[x, y]);
67 
68   // Note that, for convenience, it is also valid to create a vector of
69   // references to structs, like this:
70   // let path = builder.create_vector(&[&x, &y]);
71 
72   // Create the monster using the `Monster::create` helper function. This
73   // function accepts a `MonsterArgs` struct, which supplies all of the data
74   // needed to build a `Monster`. To supply empty/default fields, just use the
75   // Rust built-in `Default::default()` function, as demonstrated below.
76   let orc = Monster::create(&mut builder, &MonsterArgs{
77       pos: Some(&Vec3::new(1.0f32, 2.0f32, 3.0f32)),
78       mana: 150,
79       hp: 80,
80       name: Some(name),
81       inventory: Some(inventory),
82       color: Color::Red,
83       weapons: Some(weapons),
84       equipped_type: Equipment::Weapon,
85       equipped: Some(axe.as_union_value()),
86       //path: Some(path),
87       ..Default::default()
88   });
89 
90   // Serialize the root of the object, without providing a file identifier.
91   builder.finish(orc, None);
92 
93   // We now have a FlatBuffer we can store on disk or send over a network.
94 
95   // ** file/network code goes here :) **
96 
97   // Instead, we're going to access it right away (as if we just received it).
98   // This must be called after `finish()`.
99   let buf = builder.finished_data(); // Of type `&[u8]`
100 
101   // Get access to the root:
102   let monster = flatbuffers::root::<Monster>(buf).unwrap();
103 
104   // Get and test some scalar types from the FlatBuffer.
105   let hp = monster.hp();
106   let mana = monster.mana();
107   let name = monster.name();
108 
109   assert_eq!(hp, 80);
110   assert_eq!(mana, 150);  // default
111   assert_eq!(name, Some("Orc"));
112 
113   // Get and test a field of the FlatBuffer's `struct`.
114   assert!(monster.pos().is_some());
115   let pos = monster.pos().unwrap();
116   let x = pos.x();
117   let y = pos.y();
118   let z = pos.z();
119   assert_eq!(x, 1.0f32);
120   assert_eq!(y, 2.0f32);
121   assert_eq!(z, 3.0f32);
122 
123   // Get an element from the `inventory` FlatBuffer's `vector`.
124   assert!(monster.inventory().is_some());
125   let inv = monster.inventory().unwrap();
126 
127   // Note that this vector is returned as a slice, because direct access for
128   // this type, a u8 vector, is safe on all platforms:
129   let third_item = inv[2];
130   assert_eq!(third_item, 2);
131 
132   // Get and test the `weapons` FlatBuffers's `vector`.
133   assert!(monster.weapons().is_some());
134   let weps = monster.weapons().unwrap();
135   //let weps_len = weps.len();
136   let wep2 = weps.get(1);
137   let second_weapon_name = wep2.name();
138   let second_weapon_damage = wep2.damage();
139   assert_eq!(second_weapon_name, Some("Axe"));
140   assert_eq!(second_weapon_damage, 5);
141 
142   // Get and test the `Equipment` union (`equipped` field).
143   assert_eq!(monster.equipped_type(), Equipment::Weapon);
144   let equipped = monster.equipped_as_weapon().unwrap();
145   let weapon_name = equipped.name();
146   let weapon_damage = equipped.damage();
147   assert_eq!(weapon_name, Some("Axe"));
148   assert_eq!(weapon_damage, 5);
149 
150   // Get and test the `path` FlatBuffers's `vector`.
151   //assert_eq!(monster.path().unwrap().len(), 2);
152   //assert_eq!(monster.path().unwrap()[0].x(), 1.0);
153   //assert_eq!(monster.path().unwrap()[1].x(), 4.0);
154 
155   println!("The FlatBuffer was successfully created and accessed!");
156   dbg!(monster);
157 }
158 
159 #[cfg(test)]
160 #[test]
test_main()161 fn test_main() {
162     main()
163 }
164