Merge commit '0f6aab9da6fe982218a01f4a5b896e65fcced437' as 'third_party/flatbuffers'

This commit is contained in:
Siarhei Fedartsou
2024-06-22 13:33:34 +02:00
1814 changed files with 326902 additions and 0 deletions
+134
View File
@@ -0,0 +1,134 @@
/*
* Copyright 2015 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// To run, use the `csharp_sample.sh` script.
using System;
using Google.FlatBuffers;
using MyGame.Sample;
class SampleBinary
{
// Example how to use FlatBuffers to create and read binary buffers.
static void Main()
{
var builder = new FlatBufferBuilder(1);
// Create some weapons for our Monster ('Sword' and 'Axe').
var weapon1Name = builder.CreateString("Sword");
var weapon1Damage = 3;
var weapon2Name = builder.CreateString("Axe");
var weapon2Damage = 5;
// Use the `CreateWeapon()` helper function to create the weapons, since we set every field.
var weaps = new Offset<Weapon>[2];
weaps[0] = Weapon.CreateWeapon(builder, weapon1Name, (short)weapon1Damage);
weaps[1] = Weapon.CreateWeapon(builder, weapon2Name, (short)weapon2Damage);
// Serialize the FlatBuffer data.
var name = builder.CreateString("Orc");
var treasure = new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
var inv = Monster.CreateInventoryVector(builder, treasure);
var weapons = Monster.CreateWeaponsVector(builder, weaps);
var pos = Vec3.CreateVec3(builder, 1.0f, 2.0f, 3.0f);
Monster.StartMonster(builder);
Monster.AddPos(builder, pos);
Monster.AddHp(builder, (short)300);
Monster.AddName(builder, name);
Monster.AddInventory(builder, inv);
Monster.AddColor(builder, Color.Red);
Monster.AddWeapons(builder, weapons);
Monster.AddEquippedType(builder, Equipment.Weapon);
Monster.AddEquipped(builder, weaps[1].Value);
var orc = Monster.EndMonster(builder);
builder.Finish(orc.Value); // You could also call `Monster.FinishMonsterBuffer(builder, orc);`.
// We now have a FlatBuffer that we could store on disk or send over a network.
// ...Code to store to disk or send over a network goes here...
// Instead, we are going to access it right away, as if we just received it.
var buf = builder.DataBuffer;
// Get access to the root:
var monster = Monster.GetRootAsMonster(buf);
// For C#, unlike other languages, most values (except for vectors and unions) are available as
// properties instead of accessor methods.
// Note: We did not set the `Mana` field explicitly, so we get back the default value.
Assert(monster.Mana == 150, "monster.Mana", Convert.ToString(monster.Mana),
Convert.ToString(150));
Assert(monster.Hp == 300, "monster.Hp", Convert.ToString(monster.Hp), Convert.ToString(30));
Assert(monster.Name.Equals("Orc", StringComparison.Ordinal), "monster.Name", monster.Name,
"Orc");
Assert(monster.Color == Color.Red, "monster.Color", Convert.ToString(monster.Color),
Convert.ToString(Color.Red));
var vec = monster.Pos.Value;
Assert(vec.X == 1.0f, "vec.X",
Convert.ToString(vec.X), Convert.ToString(1.0f));
Assert(vec.Y == 2.0f, "vec.Y",
Convert.ToString(vec.Y), Convert.ToString(2.0f));
Assert(vec.Z == 3.0f, "vec.Z",
Convert.ToString(vec.Z), Convert.ToString(3.0f));
// Get and test the `Inventory` FlatBuffer `vector`.
for (int i = 0; i < monster.InventoryLength; i++)
{
Assert(monster.Inventory(i) == i, "monster.Inventory",
Convert.ToString(monster.Inventory(i)), Convert.ToString(i));
}
// Get and test the `Weapons` FlatBuffer `vector` of `table`s.
var expectedWeaponNames = new string[] {"Sword", "Axe"};
var expectedWeaponDamages = new short[] {3, 5};
for (int i = 0; i < monster.WeaponsLength; i++)
{
Assert(monster.Weapons(i).Value.Name.Equals(expectedWeaponNames[i], StringComparison.Ordinal),
"monster.Weapons", monster.Weapons(i).Value.Name, expectedWeaponNames[i]);
Assert(monster.Weapons(i).Value.Damage == expectedWeaponDamages[i], "monster.GetWeapons",
Convert.ToString(monster.Weapons(i).Value.Damage),
Convert.ToString(expectedWeaponDamages[i]));
}
// Get and test the `Equipped` FlatBuffer `union`.
Assert(monster.EquippedType == Equipment.Weapon, "monster.EquippedType",
Convert.ToString(monster.EquippedType), Convert.ToString(Equipment.Weapon));
var equipped = monster.Equipped<Weapon>().Value;
Assert(equipped.Name.Equals("Axe", StringComparison.Ordinal), "equipped.Name", equipped.Name,
"Axe");
Assert(equipped.Damage == 5, "equipped.Damage", Convert.ToString(equipped.Damage),
Convert.ToString(5));
Console.WriteLine("The FlatBuffer was successfully created and verified!");
}
// A helper function to handle assertions.
static void Assert(bool assertPassed, string codeExecuted, string actualValue,
string expectedValue)
{
if (assertPassed == false)
{
Console.WriteLine("Assert failed! " + codeExecuted + " (" + actualValue +
") was not equal to " + expectedValue + ".");
System.Environment.Exit(1);
}
}
}
+112
View File
@@ -0,0 +1,112 @@
/*
* Copyright 2015 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Run this file with the `java_sample.sh` script.
import MyGame.Sample.Color;
import MyGame.Sample.Equipment;
import MyGame.Sample.Monster;
import MyGame.Sample.Vec3;
import MyGame.Sample.Weapon;
import com.google.flatbuffers.FlatBufferBuilder;
import java.nio.ByteBuffer;
class SampleBinary {
// Example how to use FlatBuffers to create and read binary buffers.
public static void main(String[] args) {
FlatBufferBuilder builder = new FlatBufferBuilder(0);
// Create some weapons for our Monster ('Sword' and 'Axe').
int weaponOneName = builder.createString("Sword");
short weaponOneDamage = 3;
int weaponTwoName = builder.createString("Axe");
short weaponTwoDamage = 5;
// Use the `createWeapon()` helper function to create the weapons, since we set every field.
int[] weaps = new int[2];
weaps[0] = Weapon.createWeapon(builder, weaponOneName, weaponOneDamage);
weaps[1] = Weapon.createWeapon(builder, weaponTwoName, weaponTwoDamage);
// Serialize the FlatBuffer data.
int name = builder.createString("Orc");
byte[] treasure = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int inv = Monster.createInventoryVector(builder, treasure);
int weapons = Monster.createWeaponsVector(builder, weaps);
int pos = Vec3.createVec3(builder, 1.0f, 2.0f, 3.0f);
Monster.startMonster(builder);
Monster.addPos(builder, pos);
Monster.addName(builder, name);
Monster.addColor(builder, Color.Red);
Monster.addHp(builder, (short)300);
Monster.addInventory(builder, inv);
Monster.addWeapons(builder, weapons);
Monster.addEquippedType(builder, Equipment.Weapon);
Monster.addEquipped(builder, weaps[1]);
int orc = Monster.endMonster(builder);
builder.finish(orc); // You could also call `Monster.finishMonsterBuffer(builder, orc);`.
// We now have a FlatBuffer that can be stored on disk or sent over a network.
// ...Code to store to disk or send over a network goes here...
// Instead, we are going to access it right away, as if we just received it.
ByteBuffer buf = builder.dataBuffer();
// Get access to the root:
Monster monster = Monster.getRootAsMonster(buf);
// Note: We did not set the `mana` field explicitly, so we get back the default value.
assert monster.mana() == (short)150;
assert monster.hp() == (short)300;
assert monster.name().equals("Orc");
assert monster.color() == Color.Red;
assert monster.pos().x() == 1.0f;
assert monster.pos().y() == 2.0f;
assert monster.pos().z() == 3.0f;
// Get and test the `inventory` FlatBuffer `vector`.
for (int i = 0; i < monster.inventoryLength(); i++) {
assert monster.inventory(i) == (byte)i;
}
// Get and test the `weapons` FlatBuffer `vector` of `table`s.
String[] expectedWeaponNames = {"Sword", "Axe"};
int[] expectedWeaponDamages = {3, 5};
for (int i = 0; i < monster.weaponsLength(); i++) {
assert monster.weapons(i).name().equals(expectedWeaponNames[i]);
assert monster.weapons(i).damage() == expectedWeaponDamages[i];
}
Weapon.Vector weaponsVector = monster.weaponsVector();
for (int i = 0; i < weaponsVector.length(); i++) {
assert weaponsVector.get(i).name().equals(expectedWeaponNames[i]);
assert weaponsVector.get(i).damage() == expectedWeaponDamages[i];
}
// Get and test the `equipped` FlatBuffer `union`.
assert monster.equippedType() == Equipment.Weapon;
Weapon equipped = (Weapon)monster.equipped(new Weapon());
assert equipped.name().equals("Axe");
assert equipped.damage() == 5;
System.out.println("The FlatBuffer was successfully created and verified!");
}
}
+109
View File
@@ -0,0 +1,109 @@
/*
* Copyright 2015 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Run this file with the `java_sample.sh` script.
import MyGame.Sample.Color
import MyGame.Sample.Equipment
import MyGame.Sample.Monster
import MyGame.Sample.Vec3
import MyGame.Sample.Weapon
import com.google.flatbuffers.FlatBufferBuilder
@kotlin.ExperimentalUnsignedTypes
class SampleBinary {
companion object {
// Example how to use FlatBuffers to create and read binary buffers.
@JvmStatic
fun main(args: Array<String>) {
val builder = FlatBufferBuilder(0)
// Create some weapons for our Monster ('Sword' and 'Axe').
val weaponOneName = builder.createString("Sword")
val weaponOneDamage: Short = 3
val weaponTwoName = builder.createString("Axe")
val weaponTwoDamage: Short = 5
// Use the `createWeapon()` helper function to create the weapons, since we set every field.
val weaps = IntArray(2)
weaps[0] = Weapon.createWeapon(builder, weaponOneName, weaponOneDamage)
weaps[1] = Weapon.createWeapon(builder, weaponTwoName, weaponTwoDamage)
// Serialize the FlatBuffer data.
val name = builder.createString("Orc")
val treasure = byteArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9).asUByteArray()
val inv = Monster.createInventoryVector(builder, treasure)
val weapons = Monster.createWeaponsVector(builder, weaps)
val pos = Vec3.createVec3(builder, 1.0f, 2.0f, 3.0f)
Monster.startMonster(builder)
Monster.addPos(builder, pos)
Monster.addName(builder, name)
Monster.addColor(builder, Color.Red)
Monster.addHp(builder, 300.toShort())
Monster.addInventory(builder, inv)
Monster.addWeapons(builder, weapons)
Monster.addEquippedType(builder, Equipment.Weapon)
Monster.addEquipped(builder, weaps[1])
val orc = Monster.endMonster(builder)
builder.finish(orc) // You could also call `Monster.finishMonsterBuffer(builder, orc);`.
// We now have a FlatBuffer that can be stored on disk or sent over a network.
// ...Code to store to disk or send over a network goes here...
// Instead, we are going to access it right away, as if we just received it.
val buf = builder.dataBuffer()
// Get access to the root:
val monster = Monster.getRootAsMonster(buf)
// Note: We did not set the `mana` field explicitly, so we get back the default value.
assert(monster.mana == 150.toShort())
assert(monster.hp == 300.toShort())
assert(monster.name.equals("Orc"))
assert(monster.color == Color.Red)
assert(monster.pos!!.x == 1.0f)
assert(monster.pos!!.y == 2.0f)
assert(monster.pos!!.z == 3.0f)
// Get and test the `inventory` FlatBuffer `vector`.
for (i in 0 until monster.inventoryLength) {
assert(monster.inventory(i) == i.toUByte())
}
// Get and test the `weapons` FlatBuffer `vector` of `table`s.
val expectedWeaponNames = arrayOf("Sword", "Axe")
val expectedWeaponDamages = intArrayOf(3, 5)
for (i in 0 until monster.weaponsLength) {
assert(monster.weapons(i)!!.name.equals(expectedWeaponNames[i]))
assert(monster.weapons(i)!!.damage.toInt() == expectedWeaponDamages[i])
}
// Get and test the `equipped` FlatBuffer `union`.
assert(monster.equippedType == Equipment.Weapon)
val equipped = monster.equipped(Weapon()) as Weapon?
assert(equipped!!.name.equals("Axe"))
assert(equipped.damage == 5.toShort())
println("The FlatBuffer was successfully created and verified!")
}
}
}
+115
View File
@@ -0,0 +1,115 @@
<?php
/*
* Copyright 2015 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// To run, use the `php_sample.sh` script.
// It is recommended that you use PSR autoload when using FlatBuffers.
function __autoload($class_name) {
$class = substr($class_name, strrpos($class_name, "\\") + 1);
$root_dir = join(DIRECTORY_SEPARATOR, array(dirname(dirname(__FILE__)))); // `flatbuffers` root.
$paths = array(join(DIRECTORY_SEPARATOR, array($root_dir, "php")),
join(DIRECTORY_SEPARATOR, array($root_dir, "samples", "MyGame", "Sample")));
foreach ($paths as $path) {
$file = join(DIRECTORY_SEPARATOR, array($path, $class . ".php"));
if (file_exists($file)) {
require($file);
break;
}
}
}
// Example how to use FlatBuffers to create and read binary buffers.
function main() {
$builder = new Google\FlatBuffers\FlatbufferBuilder(0);
// Create some weapons for our Monster using the `createWeapon()` helper function.
$weapon_one = $builder->createString("Sword");
$sword = \MyGame\Sample\Weapon::CreateWeapon($builder, $weapon_one, 3);
$weapon_two = $builder->createString("Axe");
$axe = \MyGame\Sample\Weapon::CreateWeapon($builder, $weapon_two, 5);
// Serialize the FlatBuffer data.
$name = $builder->createString("Orc");
$treasure = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
$inv = \MyGame\Sample\Monster::CreateInventoryVector($builder, $treasure);
$weaps = array($sword, $axe);
$weapons = \MyGame\Sample\Monster::CreateWeaponsVector($builder, $weaps);
$pos = \MyGame\Sample\Vec3::CreateVec3($builder, 1.0, 2.0, 3.0);
\MyGame\Sample\Monster::StartMonster($builder);
\MyGame\Sample\Monster::AddPos($builder, $pos);
\MyGame\Sample\Monster::AddHp($builder, 300);
\MyGame\Sample\Monster::AddName($builder, $name);
\MyGame\Sample\Monster::AddInventory($builder, $inv);
\MyGame\Sample\Monster::AddColor($builder, \MyGame\Sample\Color::Red);
\MyGame\Sample\Monster::AddWeapons($builder, $weapons);
\MyGame\Sample\Monster::AddEquippedType($builder, \MyGame\Sample\Equipment::Weapon);
\MyGame\Sample\Monster::AddEquipped($builder, $weaps[1]);
$orc = \MyGame\Sample\Monster::EndMonster($builder);
$builder->finish($orc); // You may also call `\MyGame\Sample\Monster::FinishMonsterBuffer($builder, $orc);`.
// We now have a FlatBuffer that can be stored on disk or sent over a network.
// ...Code to store to disk or send over a network goes here...
// Instead, we are going to access it right away, as if we just received it.
$buf = $builder->dataBuffer();
// Get access to the root:
$monster = \MyGame\Sample\Monster::GetRootAsMonster($buf);
$success = true; // Tracks if an assert occurred.
// Note: We did not set the `mana` field explicitly, so we get back the default value.
$success &= assert($monster->getMana() == 150);
$success &= assert($monster->getHp() == 300);
$success &= assert($monster->getName() == "Orc");
$success &= assert($monster->getColor() == \MyGame\Sample\Color::Red);
$success &= assert($monster->getPos()->getX() == 1.0);
$success &= assert($monster->getPos()->getY() == 2.0);
$success &= assert($monster->getPos()->getZ() == 3.0);
// Get and test the `inventory` FlatBuffer `vector`.
for ($i = 0; $i < $monster->getInventoryLength(); $i++) {
$success &= assert($monster->getInventory($i) == $i);
}
// Get and test the `weapons` FlatBuffer `vector` of `table`s.
$expected_weapon_names = array("Sword", "Axe");
$expected_weapon_damages = array(3, 5);
for ($i = 0; $i < $monster->getWeaponsLength(); $i++) {
$success &= assert($monster->getWeapons($i)->getName() == $expected_weapon_names[$i]);
$success &= assert($monster->getWeapons($i)->getDamage() == $expected_weapon_damages[$i]);
}
// Get and test the `equipped` FlatBuffer `union`.
$success &= assert($monster->getEquippedType() == \MyGame\Sample\Equipment::Weapon);
$success &= assert($monster->getEquipped(new \MyGame\Sample\Weapon())->getName() == "Axe");
$success &= assert($monster->getEquipped(new \MyGame\Sample\Weapon())->getDamage() == 5);
if ($success) {
print("The FlatBuffer was successfully created and verified!\n");
}
}
main();
?>
+50
View File
@@ -0,0 +1,50 @@
#!/bin/bash
#
# Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Note: This script runs on Mac and Linux. It requires `mono` to be installed
# and `flatc` to be built (using `cmake` in the root directory).
sampledir=$(cd $(dirname $BASH_SOURCE) && pwd)
rootidr=$(cd $sampledir/.. && pwd)
currentdir=$(pwd)
if [[ "$sampledir" != "$currentdir" ]]; then
echo Error: This script must be run from inside the $sampledir directory.
echo You executed it from the $currentdir directory.
exit 1
fi
# Run `flatc`. Note: This requires you to compile using `cmake` from the
# root `/flatbuffers` directory.
if [ -e ../flatc ]; then
../flatc --csharp --gen-mutable monster.fbs
elif [ -e ../Debug/flatc ]; then
../Debug/flatc --csharp --gen-mutable monster.fbs
else
echo 'flatc' could not be found. Make sure to build FlatBuffers from the \
$rootdir directory.
exit 1
fi
echo Compiling and running the C# sample.
# Compile and execute the sample.
mcs SampleBinary.cs MyGame/Sample/*.cs ../net/FlatBuffers/*.cs
mono SampleBinary.exe
# Cleanup temporary files.
rm SampleBinary.exe
rm -rf MyGame/
+49
View File
@@ -0,0 +1,49 @@
#!/bin/bash
set -euo
#
# Copyright 2018 Dan Field. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Note: This script runs on Mac and Linux. It requires `Node.js` to be installed
# and `flatc` to be built (using `cmake` in the root directory).
sampledir=$(cd $(dirname $BASH_SOURCE) && pwd)
rootdir=$(cd $sampledir/.. && pwd)
currentdir=$(pwd)
if [[ "$sampledir" != "$currentdir" ]]; then
echo Error: This script must be run from inside the $sampledir directory.
echo You executed it from the $currentdir directory.
exit 1
fi
# Run `flatc`. Note: This requires you to compile using `cmake` from the
# root `/flatbuffers` directory.
if [ -e ../flatc ]; then
../flatc --dart -o ../dart/example/ monster.fbs
elif [ -e ../Debug/flatc ]; then
../Debug/flatc --dart -o ../dart/example/ monster.fbs
else
echo 'flatc' could not be found. Make sure to build FlatBuffers from the \
$rootdir directory.
exit 1
fi
echo Running the Dart sample.
# Execute the sample.
dart ../dart/example/example.dart
# Copy the source schema so it is distributed when published to pub.dev
cp monster.fbs ../dart/example/
+7
View File
@@ -0,0 +1,7 @@
module github.com/google/flatbuffers/samples
go 1.20
replace github.com/google/flatbuffers/go => ./go_gen
require github.com/google/flatbuffers/go v0.0.0-00010101000000-000000000000
+58
View File
@@ -0,0 +1,58 @@
#!/bin/bash
#
# Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Note: This script runs on Mac and Linux. It requires `go` to be installed
# and 'flatc' to be built (using `cmake` in the root directory).
sampledir=$(cd $(dirname $BASH_SOURCE) && pwd)
rootdir=$(cd $sampledir/.. && pwd)
currentdir=$(pwd)
if [[ "$sampledir" != "$currentdir" ]]; then
echo Error: This script must be run from inside the $sampledir directory.
echo You executed it from the $currentdir directory.
exit 1
fi
# Run `flatc`. Note: This requires you to compile using `cmake` from the
# root `/flatbuffers` directory.
if [ -e ../flatc ]; then
../flatc --go monster.fbs
elif [ -e ../Debug/flatc ]; then
../Debug/flatc --go monster.fbs
else
echo 'flatc' could not be found. Make sure to build FlatBuffers from the \
$rootdir directory.
exit 1
fi
echo Compiling and running the Go sample.
# Workaround for https://github.com/google/flatbuffers/issues/7780:
# go mod replace requires a go.mod file in the target directory,
# but there currently isn't one in the ../go directory.
# So we copy the ../go directory to go_gen and manually create go_gen/go.mod
mkdir -p ${sampledir}/go_gen
cp ${sampledir}/../go/* ${sampledir}/go_gen
( cd ${sampledir}/go_gen && go mod init github.com/google/flatbuffers/go )
# Compile and execute the sample.
go build -o go_sample sample_binary.go
./go_sample
# Clean up the temporary files.
rm -rf ${sampledir}/go_gen/
rm go_sample
+51
View File
@@ -0,0 +1,51 @@
#!/bin/bash
#
# Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Note: This script runs on Mac and Linux. It requires `java` to be installed
# and `flatc` to be built (using `cmake` in the root directory).
sampledir=$(cd $(dirname $BASH_SOURCE) && pwd)
rootdir=$(cd $sampledir/.. && pwd)
currentdir=$(pwd)
if [[ "$sampledir" != "$currentdir" ]]; then
echo Error: This script must be run from inside the $sampledir directory.
echo You executed it from the $currentdir directory.
exit 1
fi
# Run `flatc`. Note: This requires you to compile using `cmake` from the
# root `/flatbuffers` directory.
if [ -e ../flatc ]; then
../flatc --java --gen-mutable monster.fbs
elif [ -e ../Debug/flatc ]; then
../Debug/flatc --java --gen-mutable monster.fbs
else
echo 'flatc' could not be found. Make sure to build FlatBuffers from the \
$rootdir directory.
exit 1
fi
echo Compiling and running the Java sample.
# Compile and execute the sample.
javac -classpath ${sampledir}/../java:${sampledir} SampleBinary.java
java -classpath ${sampledir}/../java:${sampledir} SampleBinary
# Cleanup temporary files.
rm -rf MyGame/
rm ${sampledir}/../java/com/google/flatbuffers/*.class
rm *.class
+48
View File
@@ -0,0 +1,48 @@
#!/bin/bash
#
# Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Note: This script runs on Mac and Linux. It requires `Node.js` to be installed
# and `flatc` to be built (using `cmake` in the root directory).
sampledir=$(cd $(dirname $BASH_SOURCE) && pwd)
rootdir=$(cd $sampledir/.. && pwd)
currentdir=$(pwd)
if [[ "$sampledir" != "$currentdir" ]]; then
echo Error: This script must be run from inside the $sampledir directory.
echo You executed it from the $currentdir directory.
exit 1
fi
# Run `flatc`. Note: This requires you to compile using `cmake` from the
# root `/flatbuffers` directory.
if [ -e ../flatc ]; then
../flatc --js monster.fbs
elif [ -e ../Debug/flatc ]; then
../Debug/flatc --js monster.fbs
else
echo 'flatc' could not be found. Make sure to build FlatBuffers from the \
$rootdir directory.
exit 1
fi
echo Running the JavaScript sample.
# Execute the sample.
node samplebinary.js
# Cleanup temporary files.
rm monster_generated.js
+60
View File
@@ -0,0 +1,60 @@
#!/bin/bash
#
# Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Note: This script runs on Mac and Linux. It requires `kotlin` to be installed
# and `flatc` to be built (using `cmake` in the root directory).
sampledir=$(cd $(dirname $BASH_SOURCE) && pwd)
rootdir=$(cd $sampledir/.. && pwd)
currentdir=$(pwd)
if [[ "$sampledir" != "$currentdir" ]]; then
echo Error: This script must be run from inside the $sampledir directory.
echo You executed it from the $currentdir directory.
exit 1
fi
# Run `flatc`. Note: This requires you to compile using `cmake` from the
# root `/flatbuffers` directory.
if [ -e ../flatc ]; then
echo "compiling now"
../flatc --kotlin --gen-mutable monster.fbs
elif [ -e ../Debug/flatc ]; then
../Debug/flatc --kotlin --gen-mutable monster.fbs
else
echo 'flatc' could not be found. Make sure to build FlatBuffers from the \
$rootdir directory.
exit 1
fi
echo Compiling and running the Kotlin sample
all_kt_files=`find $sampledir -name "*.kt" -print`
# Run test
mkdir -v "${sampledir}/kotlin"
echo Compiling Java Runtime
javac ${rootdir}/java/com/google/flatbuffers/*.java -d ${sampledir}/kotlin
echo Compiling Kotlin source
kotlinc -classpath ${sampledir}/../java:${sampledir}/kotlin $all_kt_files SampleBinary.kt -include-runtime -d ${sampledir}/kotlin
# Make jar
echo Making jar
jar cvf ${sampledir}/kotlin/kotlin_sample.jar -C ${sampledir}/kotlin . > /dev/null
echo Running test
kotlin -cp ${sampledir}/kotlin/kotlin_sample.jar SampleBinary
# Cleanup temporary files.
rm -rf MyGame/
# rm -rf ${sampledir}/kotlin
@@ -0,0 +1,11 @@
-- automatically generated by the FlatBuffers compiler, do not modify
-- namespace: Sample
local Color = {
Red = 0,
Green = 1,
Blue = 2,
}
return Color -- return the module
@@ -0,0 +1,10 @@
-- automatically generated by the FlatBuffers compiler, do not modify
-- namespace: Sample
local Equipment = {
NONE = 0,
Weapon = 1,
}
return Equipment -- return the module
@@ -0,0 +1,122 @@
-- automatically generated by the FlatBuffers compiler, do not modify
-- namespace: Sample
local flatbuffers = require('flatbuffers')
local Monster = {} -- the module
local Monster_mt = {} -- the class metatable
function Monster.New()
local o = {}
setmetatable(o, {__index = Monster_mt})
return o
end
function Monster.GetRootAsMonster(buf, offset)
local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)
local o = Monster.New()
o:Init(buf, n + offset)
return o
end
function Monster_mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function Monster_mt:Pos()
local o = self.view:Offset(4)
if o ~= 0 then
local x = o + self.view.pos
local obj = require('MyGame.Sample.Vec3').New()
obj:Init(self.view.bytes, x)
return obj
end
end
function Monster_mt:Mana()
local o = self.view:Offset(6)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Int16, o + self.view.pos)
end
return 150
end
function Monster_mt:Hp()
local o = self.view:Offset(8)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Int16, o + self.view.pos)
end
return 100
end
function Monster_mt:Name()
local o = self.view:Offset(10)
if o ~= 0 then
return self.view:String(o + self.view.pos)
end
end
function Monster_mt:Inventory(j)
local o = self.view:Offset(14)
if o ~= 0 then
local a = self.view:Vector(o)
return self.view:Get(flatbuffers.N.Uint8, a + ((j-1) * 1))
end
return 0
end
function Monster_mt:InventoryLength()
local o = self.view:Offset(14)
if o ~= 0 then
return self.view:VectorLen(o)
end
return 0
end
function Monster_mt:Color()
local o = self.view:Offset(16)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Int8, o + self.view.pos)
end
return 2
end
function Monster_mt:Weapons(j)
local o = self.view:Offset(18)
if o ~= 0 then
local x = self.view:Vector(o)
x = x + ((j-1) * 4)
x = self.view:Indirect(x)
local obj = require('MyGame.Sample.Weapon').New()
obj:Init(self.view.bytes, x)
return obj
end
end
function Monster_mt:WeaponsLength()
local o = self.view:Offset(18)
if o ~= 0 then
return self.view:VectorLen(o)
end
return 0
end
function Monster_mt:EquippedType()
local o = self.view:Offset(20)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Uint8, o + self.view.pos)
end
return 0
end
function Monster_mt:Equipped()
local o = self.view:Offset(22)
if o ~= 0 then
local obj = flatbuffers.view.New(require('flatbuffers.binaryarray').New(0), 0)
self.view:Union(obj, o)
return obj
end
end
function Monster.Start(builder) builder:StartObject(10) end
function Monster.AddPos(builder, pos) builder:PrependStructSlot(0, pos, 0) end
function Monster.AddMana(builder, mana) builder:PrependInt16Slot(1, mana, 150) end
function Monster.AddHp(builder, hp) builder:PrependInt16Slot(2, hp, 100) end
function Monster.AddName(builder, name) builder:PrependUOffsetTRelativeSlot(3, name, 0) end
function Monster.AddInventory(builder, inventory) builder:PrependUOffsetTRelativeSlot(5, inventory, 0) end
function Monster.StartInventoryVector(builder, numElems) return builder:StartVector(1, numElems, 1) end
function Monster.AddColor(builder, color) builder:PrependInt8Slot(6, color, 2) end
function Monster.AddWeapons(builder, weapons) builder:PrependUOffsetTRelativeSlot(7, weapons, 0) end
function Monster.StartWeaponsVector(builder, numElems) return builder:StartVector(4, numElems, 4) end
function Monster.AddEquippedType(builder, equippedType) builder:PrependUint8Slot(8, equippedType, 0) end
function Monster.AddEquipped(builder, equipped) builder:PrependUOffsetTRelativeSlot(9, equipped, 0) end
function Monster.End(builder) return builder:EndObject() end
return Monster -- return the module
@@ -0,0 +1,35 @@
-- automatically generated by the FlatBuffers compiler, do not modify
-- namespace: Sample
local flatbuffers = require('flatbuffers')
local Vec3 = {} -- the module
local Vec3_mt = {} -- the class metatable
function Vec3.New()
local o = {}
setmetatable(o, {__index = Vec3_mt})
return o
end
function Vec3_mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function Vec3_mt:X()
return self.view:Get(flatbuffers.N.Float32, self.view.pos + 0)
end
function Vec3_mt:Y()
return self.view:Get(flatbuffers.N.Float32, self.view.pos + 4)
end
function Vec3_mt:Z()
return self.view:Get(flatbuffers.N.Float32, self.view.pos + 8)
end
function Vec3.CreateVec3(builder, x, y, z)
builder:Prep(4, 12)
builder:PrependFloat32(z)
builder:PrependFloat32(y)
builder:PrependFloat32(x)
return builder:Offset()
end
return Vec3 -- return the module
@@ -0,0 +1,42 @@
-- automatically generated by the FlatBuffers compiler, do not modify
-- namespace: Sample
local flatbuffers = require('flatbuffers')
local Weapon = {} -- the module
local Weapon_mt = {} -- the class metatable
function Weapon.New()
local o = {}
setmetatable(o, {__index = Weapon_mt})
return o
end
function Weapon.GetRootAsWeapon(buf, offset)
local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)
local o = Weapon.New()
o:Init(buf, n + offset)
return o
end
function Weapon_mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function Weapon_mt:Name()
local o = self.view:Offset(4)
if o ~= 0 then
return self.view:String(o + self.view.pos)
end
end
function Weapon_mt:Damage()
local o = self.view:Offset(6)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Int16, o + self.view.pos)
end
return 0
end
function Weapon.Start(builder) builder:StartObject(2) end
function Weapon.AddName(builder, name) builder:PrependUOffsetTRelativeSlot(0, name, 0) end
function Weapon.AddDamage(builder, damage) builder:PrependInt16Slot(1, damage, 0) end
function Weapon.End(builder) return builder:EndObject() end
return Weapon -- return the module
Binary file not shown.
+33
View File
@@ -0,0 +1,33 @@
// Example IDL file for our monster's schema.
namespace MyGame.Sample;
enum Color:byte { Red = 0, Green, Blue = 2 }
union Equipment { Weapon } // Optionally add more tables.
struct Vec3 {
x:float;
y:float;
z:float;
}
table Monster {
pos:Vec3;
mana:short = 150;
hp:short = 100;
name:string;
friendly:bool = false (deprecated);
inventory:[ubyte];
color:Color = Blue;
weapons:[Weapon];
equipped:Equipment;
path:[Vec3];
}
table Weapon {
name:string;
damage:short;
}
root_type Monster;
+923
View File
@@ -0,0 +1,923 @@
// automatically generated by the FlatBuffers compiler, do not modify
#ifndef FLATBUFFERS_GENERATED_MONSTER_MYGAME_SAMPLE_H_
#define FLATBUFFERS_GENERATED_MONSTER_MYGAME_SAMPLE_H_
#include "flatbuffers/flatbuffers.h"
// Ensure the included flatbuffers.h is the same version as when this file was
// generated, otherwise it may not be compatible.
static_assert(FLATBUFFERS_VERSION_MAJOR == 24 &&
FLATBUFFERS_VERSION_MINOR == 3 &&
FLATBUFFERS_VERSION_REVISION == 25,
"Non-compatible flatbuffers version included");
namespace MyGame {
namespace Sample {
struct Vec3;
struct Monster;
struct MonsterBuilder;
struct MonsterT;
struct Weapon;
struct WeaponBuilder;
struct WeaponT;
bool operator==(const Vec3 &lhs, const Vec3 &rhs);
bool operator!=(const Vec3 &lhs, const Vec3 &rhs);
bool operator==(const MonsterT &lhs, const MonsterT &rhs);
bool operator!=(const MonsterT &lhs, const MonsterT &rhs);
bool operator==(const WeaponT &lhs, const WeaponT &rhs);
bool operator!=(const WeaponT &lhs, const WeaponT &rhs);
inline const ::flatbuffers::TypeTable *Vec3TypeTable();
inline const ::flatbuffers::TypeTable *MonsterTypeTable();
inline const ::flatbuffers::TypeTable *WeaponTypeTable();
enum Color : int8_t {
Color_Red = 0,
Color_Green = 1,
Color_Blue = 2,
Color_MIN = Color_Red,
Color_MAX = Color_Blue
};
inline const Color (&EnumValuesColor())[3] {
static const Color values[] = {
Color_Red,
Color_Green,
Color_Blue
};
return values;
}
inline const char * const *EnumNamesColor() {
static const char * const names[4] = {
"Red",
"Green",
"Blue",
nullptr
};
return names;
}
inline const char *EnumNameColor(Color e) {
if (::flatbuffers::IsOutRange(e, Color_Red, Color_Blue)) return "";
const size_t index = static_cast<size_t>(e);
return EnumNamesColor()[index];
}
enum Equipment : uint8_t {
Equipment_NONE = 0,
Equipment_Weapon = 1,
Equipment_MIN = Equipment_NONE,
Equipment_MAX = Equipment_Weapon
};
inline const Equipment (&EnumValuesEquipment())[2] {
static const Equipment values[] = {
Equipment_NONE,
Equipment_Weapon
};
return values;
}
inline const char * const *EnumNamesEquipment() {
static const char * const names[3] = {
"NONE",
"Weapon",
nullptr
};
return names;
}
inline const char *EnumNameEquipment(Equipment e) {
if (::flatbuffers::IsOutRange(e, Equipment_NONE, Equipment_Weapon)) return "";
const size_t index = static_cast<size_t>(e);
return EnumNamesEquipment()[index];
}
template<typename T> struct EquipmentTraits {
static const Equipment enum_value = Equipment_NONE;
};
template<> struct EquipmentTraits<MyGame::Sample::Weapon> {
static const Equipment enum_value = Equipment_Weapon;
};
template<typename T> struct EquipmentUnionTraits {
static const Equipment enum_value = Equipment_NONE;
};
template<> struct EquipmentUnionTraits<MyGame::Sample::WeaponT> {
static const Equipment enum_value = Equipment_Weapon;
};
struct EquipmentUnion {
Equipment type;
void *value;
EquipmentUnion() : type(Equipment_NONE), value(nullptr) {}
EquipmentUnion(EquipmentUnion&& u) FLATBUFFERS_NOEXCEPT :
type(Equipment_NONE), value(nullptr)
{ std::swap(type, u.type); std::swap(value, u.value); }
EquipmentUnion(const EquipmentUnion &);
EquipmentUnion &operator=(const EquipmentUnion &u)
{ EquipmentUnion t(u); std::swap(type, t.type); std::swap(value, t.value); return *this; }
EquipmentUnion &operator=(EquipmentUnion &&u) FLATBUFFERS_NOEXCEPT
{ std::swap(type, u.type); std::swap(value, u.value); return *this; }
~EquipmentUnion() { Reset(); }
void Reset();
template <typename T>
void Set(T&& val) {
typedef typename std::remove_reference<T>::type RT;
Reset();
type = EquipmentUnionTraits<RT>::enum_value;
if (type != Equipment_NONE) {
value = new RT(std::forward<T>(val));
}
}
static void *UnPack(const void *obj, Equipment type, const ::flatbuffers::resolver_function_t *resolver);
::flatbuffers::Offset<void> Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr) const;
MyGame::Sample::WeaponT *AsWeapon() {
return type == Equipment_Weapon ?
reinterpret_cast<MyGame::Sample::WeaponT *>(value) : nullptr;
}
const MyGame::Sample::WeaponT *AsWeapon() const {
return type == Equipment_Weapon ?
reinterpret_cast<const MyGame::Sample::WeaponT *>(value) : nullptr;
}
};
inline bool operator==(const EquipmentUnion &lhs, const EquipmentUnion &rhs) {
if (lhs.type != rhs.type) return false;
switch (lhs.type) {
case Equipment_NONE: {
return true;
}
case Equipment_Weapon: {
return *(reinterpret_cast<const MyGame::Sample::WeaponT *>(lhs.value)) ==
*(reinterpret_cast<const MyGame::Sample::WeaponT *>(rhs.value));
}
default: {
return false;
}
}
}
inline bool operator!=(const EquipmentUnion &lhs, const EquipmentUnion &rhs) {
return !(lhs == rhs);
}
bool VerifyEquipment(::flatbuffers::Verifier &verifier, const void *obj, Equipment type);
bool VerifyEquipmentVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset<void>> *values, const ::flatbuffers::Vector<uint8_t> *types);
FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Vec3 FLATBUFFERS_FINAL_CLASS {
private:
float x_;
float y_;
float z_;
public:
static const ::flatbuffers::TypeTable *MiniReflectTypeTable() {
return Vec3TypeTable();
}
Vec3()
: x_(0),
y_(0),
z_(0) {
}
Vec3(float _x, float _y, float _z)
: x_(::flatbuffers::EndianScalar(_x)),
y_(::flatbuffers::EndianScalar(_y)),
z_(::flatbuffers::EndianScalar(_z)) {
}
float x() const {
return ::flatbuffers::EndianScalar(x_);
}
void mutate_x(float _x) {
::flatbuffers::WriteScalar(&x_, _x);
}
float y() const {
return ::flatbuffers::EndianScalar(y_);
}
void mutate_y(float _y) {
::flatbuffers::WriteScalar(&y_, _y);
}
float z() const {
return ::flatbuffers::EndianScalar(z_);
}
void mutate_z(float _z) {
::flatbuffers::WriteScalar(&z_, _z);
}
};
FLATBUFFERS_STRUCT_END(Vec3, 12);
inline bool operator==(const Vec3 &lhs, const Vec3 &rhs) {
return
(lhs.x() == rhs.x()) &&
(lhs.y() == rhs.y()) &&
(lhs.z() == rhs.z());
}
inline bool operator!=(const Vec3 &lhs, const Vec3 &rhs) {
return !(lhs == rhs);
}
struct MonsterT : public ::flatbuffers::NativeTable {
typedef Monster TableType;
std::unique_ptr<MyGame::Sample::Vec3> pos{};
int16_t mana = 150;
int16_t hp = 100;
std::string name{};
std::vector<uint8_t> inventory{};
MyGame::Sample::Color color = MyGame::Sample::Color_Blue;
std::vector<std::unique_ptr<MyGame::Sample::WeaponT>> weapons{};
MyGame::Sample::EquipmentUnion equipped{};
std::vector<MyGame::Sample::Vec3> path{};
MonsterT() = default;
MonsterT(const MonsterT &o);
MonsterT(MonsterT&&) FLATBUFFERS_NOEXCEPT = default;
MonsterT &operator=(MonsterT o) FLATBUFFERS_NOEXCEPT;
};
struct Monster FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table {
typedef MonsterT NativeTableType;
typedef MonsterBuilder Builder;
static const ::flatbuffers::TypeTable *MiniReflectTypeTable() {
return MonsterTypeTable();
}
enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
VT_POS = 4,
VT_MANA = 6,
VT_HP = 8,
VT_NAME = 10,
VT_INVENTORY = 14,
VT_COLOR = 16,
VT_WEAPONS = 18,
VT_EQUIPPED_TYPE = 20,
VT_EQUIPPED = 22,
VT_PATH = 24
};
const MyGame::Sample::Vec3 *pos() const {
return GetStruct<const MyGame::Sample::Vec3 *>(VT_POS);
}
MyGame::Sample::Vec3 *mutable_pos() {
return GetStruct<MyGame::Sample::Vec3 *>(VT_POS);
}
int16_t mana() const {
return GetField<int16_t>(VT_MANA, 150);
}
bool mutate_mana(int16_t _mana = 150) {
return SetField<int16_t>(VT_MANA, _mana, 150);
}
int16_t hp() const {
return GetField<int16_t>(VT_HP, 100);
}
bool mutate_hp(int16_t _hp = 100) {
return SetField<int16_t>(VT_HP, _hp, 100);
}
const ::flatbuffers::String *name() const {
return GetPointer<const ::flatbuffers::String *>(VT_NAME);
}
::flatbuffers::String *mutable_name() {
return GetPointer<::flatbuffers::String *>(VT_NAME);
}
const ::flatbuffers::Vector<uint8_t> *inventory() const {
return GetPointer<const ::flatbuffers::Vector<uint8_t> *>(VT_INVENTORY);
}
::flatbuffers::Vector<uint8_t> *mutable_inventory() {
return GetPointer<::flatbuffers::Vector<uint8_t> *>(VT_INVENTORY);
}
MyGame::Sample::Color color() const {
return static_cast<MyGame::Sample::Color>(GetField<int8_t>(VT_COLOR, 2));
}
bool mutate_color(MyGame::Sample::Color _color = static_cast<MyGame::Sample::Color>(2)) {
return SetField<int8_t>(VT_COLOR, static_cast<int8_t>(_color), 2);
}
const ::flatbuffers::Vector<::flatbuffers::Offset<MyGame::Sample::Weapon>> *weapons() const {
return GetPointer<const ::flatbuffers::Vector<::flatbuffers::Offset<MyGame::Sample::Weapon>> *>(VT_WEAPONS);
}
::flatbuffers::Vector<::flatbuffers::Offset<MyGame::Sample::Weapon>> *mutable_weapons() {
return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset<MyGame::Sample::Weapon>> *>(VT_WEAPONS);
}
MyGame::Sample::Equipment equipped_type() const {
return static_cast<MyGame::Sample::Equipment>(GetField<uint8_t>(VT_EQUIPPED_TYPE, 0));
}
const void *equipped() const {
return GetPointer<const void *>(VT_EQUIPPED);
}
template<typename T> const T *equipped_as() const;
const MyGame::Sample::Weapon *equipped_as_Weapon() const {
return equipped_type() == MyGame::Sample::Equipment_Weapon ? static_cast<const MyGame::Sample::Weapon *>(equipped()) : nullptr;
}
void *mutable_equipped() {
return GetPointer<void *>(VT_EQUIPPED);
}
const ::flatbuffers::Vector<const MyGame::Sample::Vec3 *> *path() const {
return GetPointer<const ::flatbuffers::Vector<const MyGame::Sample::Vec3 *> *>(VT_PATH);
}
::flatbuffers::Vector<const MyGame::Sample::Vec3 *> *mutable_path() {
return GetPointer<::flatbuffers::Vector<const MyGame::Sample::Vec3 *> *>(VT_PATH);
}
bool Verify(::flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyField<MyGame::Sample::Vec3>(verifier, VT_POS, 4) &&
VerifyField<int16_t>(verifier, VT_MANA, 2) &&
VerifyField<int16_t>(verifier, VT_HP, 2) &&
VerifyOffset(verifier, VT_NAME) &&
verifier.VerifyString(name()) &&
VerifyOffset(verifier, VT_INVENTORY) &&
verifier.VerifyVector(inventory()) &&
VerifyField<int8_t>(verifier, VT_COLOR, 1) &&
VerifyOffset(verifier, VT_WEAPONS) &&
verifier.VerifyVector(weapons()) &&
verifier.VerifyVectorOfTables(weapons()) &&
VerifyField<uint8_t>(verifier, VT_EQUIPPED_TYPE, 1) &&
VerifyOffset(verifier, VT_EQUIPPED) &&
VerifyEquipment(verifier, equipped(), equipped_type()) &&
VerifyOffset(verifier, VT_PATH) &&
verifier.VerifyVector(path()) &&
verifier.EndTable();
}
MonsterT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const;
void UnPackTo(MonsterT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const;
static ::flatbuffers::Offset<Monster> Pack(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr);
};
template<> inline const MyGame::Sample::Weapon *Monster::equipped_as<MyGame::Sample::Weapon>() const {
return equipped_as_Weapon();
}
struct MonsterBuilder {
typedef Monster Table;
::flatbuffers::FlatBufferBuilder &fbb_;
::flatbuffers::uoffset_t start_;
void add_pos(const MyGame::Sample::Vec3 *pos) {
fbb_.AddStruct(Monster::VT_POS, pos);
}
void add_mana(int16_t mana) {
fbb_.AddElement<int16_t>(Monster::VT_MANA, mana, 150);
}
void add_hp(int16_t hp) {
fbb_.AddElement<int16_t>(Monster::VT_HP, hp, 100);
}
void add_name(::flatbuffers::Offset<::flatbuffers::String> name) {
fbb_.AddOffset(Monster::VT_NAME, name);
}
void add_inventory(::flatbuffers::Offset<::flatbuffers::Vector<uint8_t>> inventory) {
fbb_.AddOffset(Monster::VT_INVENTORY, inventory);
}
void add_color(MyGame::Sample::Color color) {
fbb_.AddElement<int8_t>(Monster::VT_COLOR, static_cast<int8_t>(color), 2);
}
void add_weapons(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<MyGame::Sample::Weapon>>> weapons) {
fbb_.AddOffset(Monster::VT_WEAPONS, weapons);
}
void add_equipped_type(MyGame::Sample::Equipment equipped_type) {
fbb_.AddElement<uint8_t>(Monster::VT_EQUIPPED_TYPE, static_cast<uint8_t>(equipped_type), 0);
}
void add_equipped(::flatbuffers::Offset<void> equipped) {
fbb_.AddOffset(Monster::VT_EQUIPPED, equipped);
}
void add_path(::flatbuffers::Offset<::flatbuffers::Vector<const MyGame::Sample::Vec3 *>> path) {
fbb_.AddOffset(Monster::VT_PATH, path);
}
explicit MonsterBuilder(::flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
}
::flatbuffers::Offset<Monster> Finish() {
const auto end = fbb_.EndTable(start_);
auto o = ::flatbuffers::Offset<Monster>(end);
return o;
}
};
inline ::flatbuffers::Offset<Monster> CreateMonster(
::flatbuffers::FlatBufferBuilder &_fbb,
const MyGame::Sample::Vec3 *pos = nullptr,
int16_t mana = 150,
int16_t hp = 100,
::flatbuffers::Offset<::flatbuffers::String> name = 0,
::flatbuffers::Offset<::flatbuffers::Vector<uint8_t>> inventory = 0,
MyGame::Sample::Color color = MyGame::Sample::Color_Blue,
::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<MyGame::Sample::Weapon>>> weapons = 0,
MyGame::Sample::Equipment equipped_type = MyGame::Sample::Equipment_NONE,
::flatbuffers::Offset<void> equipped = 0,
::flatbuffers::Offset<::flatbuffers::Vector<const MyGame::Sample::Vec3 *>> path = 0) {
MonsterBuilder builder_(_fbb);
builder_.add_path(path);
builder_.add_equipped(equipped);
builder_.add_weapons(weapons);
builder_.add_inventory(inventory);
builder_.add_name(name);
builder_.add_pos(pos);
builder_.add_hp(hp);
builder_.add_mana(mana);
builder_.add_equipped_type(equipped_type);
builder_.add_color(color);
return builder_.Finish();
}
inline ::flatbuffers::Offset<Monster> CreateMonsterDirect(
::flatbuffers::FlatBufferBuilder &_fbb,
const MyGame::Sample::Vec3 *pos = nullptr,
int16_t mana = 150,
int16_t hp = 100,
const char *name = nullptr,
const std::vector<uint8_t> *inventory = nullptr,
MyGame::Sample::Color color = MyGame::Sample::Color_Blue,
const std::vector<::flatbuffers::Offset<MyGame::Sample::Weapon>> *weapons = nullptr,
MyGame::Sample::Equipment equipped_type = MyGame::Sample::Equipment_NONE,
::flatbuffers::Offset<void> equipped = 0,
const std::vector<MyGame::Sample::Vec3> *path = nullptr) {
auto name__ = name ? _fbb.CreateString(name) : 0;
auto inventory__ = inventory ? _fbb.CreateVector<uint8_t>(*inventory) : 0;
auto weapons__ = weapons ? _fbb.CreateVector<::flatbuffers::Offset<MyGame::Sample::Weapon>>(*weapons) : 0;
auto path__ = path ? _fbb.CreateVectorOfStructs<MyGame::Sample::Vec3>(*path) : 0;
return MyGame::Sample::CreateMonster(
_fbb,
pos,
mana,
hp,
name__,
inventory__,
color,
weapons__,
equipped_type,
equipped,
path__);
}
::flatbuffers::Offset<Monster> CreateMonster(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr);
struct WeaponT : public ::flatbuffers::NativeTable {
typedef Weapon TableType;
std::string name{};
int16_t damage = 0;
};
struct Weapon FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table {
typedef WeaponT NativeTableType;
typedef WeaponBuilder Builder;
static const ::flatbuffers::TypeTable *MiniReflectTypeTable() {
return WeaponTypeTable();
}
enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
VT_NAME = 4,
VT_DAMAGE = 6
};
const ::flatbuffers::String *name() const {
return GetPointer<const ::flatbuffers::String *>(VT_NAME);
}
::flatbuffers::String *mutable_name() {
return GetPointer<::flatbuffers::String *>(VT_NAME);
}
int16_t damage() const {
return GetField<int16_t>(VT_DAMAGE, 0);
}
bool mutate_damage(int16_t _damage = 0) {
return SetField<int16_t>(VT_DAMAGE, _damage, 0);
}
bool Verify(::flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyOffset(verifier, VT_NAME) &&
verifier.VerifyString(name()) &&
VerifyField<int16_t>(verifier, VT_DAMAGE, 2) &&
verifier.EndTable();
}
WeaponT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const;
void UnPackTo(WeaponT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const;
static ::flatbuffers::Offset<Weapon> Pack(::flatbuffers::FlatBufferBuilder &_fbb, const WeaponT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr);
};
struct WeaponBuilder {
typedef Weapon Table;
::flatbuffers::FlatBufferBuilder &fbb_;
::flatbuffers::uoffset_t start_;
void add_name(::flatbuffers::Offset<::flatbuffers::String> name) {
fbb_.AddOffset(Weapon::VT_NAME, name);
}
void add_damage(int16_t damage) {
fbb_.AddElement<int16_t>(Weapon::VT_DAMAGE, damage, 0);
}
explicit WeaponBuilder(::flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
}
::flatbuffers::Offset<Weapon> Finish() {
const auto end = fbb_.EndTable(start_);
auto o = ::flatbuffers::Offset<Weapon>(end);
return o;
}
};
inline ::flatbuffers::Offset<Weapon> CreateWeapon(
::flatbuffers::FlatBufferBuilder &_fbb,
::flatbuffers::Offset<::flatbuffers::String> name = 0,
int16_t damage = 0) {
WeaponBuilder builder_(_fbb);
builder_.add_name(name);
builder_.add_damage(damage);
return builder_.Finish();
}
inline ::flatbuffers::Offset<Weapon> CreateWeaponDirect(
::flatbuffers::FlatBufferBuilder &_fbb,
const char *name = nullptr,
int16_t damage = 0) {
auto name__ = name ? _fbb.CreateString(name) : 0;
return MyGame::Sample::CreateWeapon(
_fbb,
name__,
damage);
}
::flatbuffers::Offset<Weapon> CreateWeapon(::flatbuffers::FlatBufferBuilder &_fbb, const WeaponT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr);
inline bool operator==(const MonsterT &lhs, const MonsterT &rhs) {
return
((lhs.pos == rhs.pos) || (lhs.pos && rhs.pos && *lhs.pos == *rhs.pos)) &&
(lhs.mana == rhs.mana) &&
(lhs.hp == rhs.hp) &&
(lhs.name == rhs.name) &&
(lhs.inventory == rhs.inventory) &&
(lhs.color == rhs.color) &&
(lhs.weapons.size() == rhs.weapons.size() && std::equal(lhs.weapons.cbegin(), lhs.weapons.cend(), rhs.weapons.cbegin(), [](std::unique_ptr<MyGame::Sample::WeaponT> const &a, std::unique_ptr<MyGame::Sample::WeaponT> const &b) { return (a == b) || (a && b && *a == *b); })) &&
(lhs.equipped == rhs.equipped) &&
(lhs.path == rhs.path);
}
inline bool operator!=(const MonsterT &lhs, const MonsterT &rhs) {
return !(lhs == rhs);
}
inline MonsterT::MonsterT(const MonsterT &o)
: pos((o.pos) ? new MyGame::Sample::Vec3(*o.pos) : nullptr),
mana(o.mana),
hp(o.hp),
name(o.name),
inventory(o.inventory),
color(o.color),
equipped(o.equipped),
path(o.path) {
weapons.reserve(o.weapons.size());
for (const auto &weapons_ : o.weapons) { weapons.emplace_back((weapons_) ? new MyGame::Sample::WeaponT(*weapons_) : nullptr); }
}
inline MonsterT &MonsterT::operator=(MonsterT o) FLATBUFFERS_NOEXCEPT {
std::swap(pos, o.pos);
std::swap(mana, o.mana);
std::swap(hp, o.hp);
std::swap(name, o.name);
std::swap(inventory, o.inventory);
std::swap(color, o.color);
std::swap(weapons, o.weapons);
std::swap(equipped, o.equipped);
std::swap(path, o.path);
return *this;
}
inline MonsterT *Monster::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const {
auto _o = std::unique_ptr<MonsterT>(new MonsterT());
UnPackTo(_o.get(), _resolver);
return _o.release();
}
inline void Monster::UnPackTo(MonsterT *_o, const ::flatbuffers::resolver_function_t *_resolver) const {
(void)_o;
(void)_resolver;
{ auto _e = pos(); if (_e) _o->pos = std::unique_ptr<MyGame::Sample::Vec3>(new MyGame::Sample::Vec3(*_e)); }
{ auto _e = mana(); _o->mana = _e; }
{ auto _e = hp(); _o->hp = _e; }
{ auto _e = name(); if (_e) _o->name = _e->str(); }
{ auto _e = inventory(); if (_e) { _o->inventory.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->inventory.begin()); } }
{ auto _e = color(); _o->color = _e; }
{ auto _e = weapons(); if (_e) { _o->weapons.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->weapons[_i]) { _e->Get(_i)->UnPackTo(_o->weapons[_i].get(), _resolver); } else { _o->weapons[_i] = std::unique_ptr<MyGame::Sample::WeaponT>(_e->Get(_i)->UnPack(_resolver)); }; } } else { _o->weapons.resize(0); } }
{ auto _e = equipped_type(); _o->equipped.type = _e; }
{ auto _e = equipped(); if (_e) _o->equipped.value = MyGame::Sample::EquipmentUnion::UnPack(_e, equipped_type(), _resolver); }
{ auto _e = path(); if (_e) { _o->path.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->path[_i] = *_e->Get(_i); } } else { _o->path.resize(0); } }
}
inline ::flatbuffers::Offset<Monster> Monster::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) {
return CreateMonster(_fbb, _o, _rehasher);
}
inline ::flatbuffers::Offset<Monster> CreateMonster(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) {
(void)_rehasher;
(void)_o;
struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const MonsterT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va;
auto _pos = _o->pos ? _o->pos.get() : nullptr;
auto _mana = _o->mana;
auto _hp = _o->hp;
auto _name = _o->name.empty() ? 0 : _fbb.CreateString(_o->name);
auto _inventory = _o->inventory.size() ? _fbb.CreateVector(_o->inventory) : 0;
auto _color = _o->color;
auto _weapons = _o->weapons.size() ? _fbb.CreateVector<::flatbuffers::Offset<MyGame::Sample::Weapon>> (_o->weapons.size(), [](size_t i, _VectorArgs *__va) { return CreateWeapon(*__va->__fbb, __va->__o->weapons[i].get(), __va->__rehasher); }, &_va ) : 0;
auto _equipped_type = _o->equipped.type;
auto _equipped = _o->equipped.Pack(_fbb);
auto _path = _o->path.size() ? _fbb.CreateVectorOfStructs(_o->path) : 0;
return MyGame::Sample::CreateMonster(
_fbb,
_pos,
_mana,
_hp,
_name,
_inventory,
_color,
_weapons,
_equipped_type,
_equipped,
_path);
}
inline bool operator==(const WeaponT &lhs, const WeaponT &rhs) {
return
(lhs.name == rhs.name) &&
(lhs.damage == rhs.damage);
}
inline bool operator!=(const WeaponT &lhs, const WeaponT &rhs) {
return !(lhs == rhs);
}
inline WeaponT *Weapon::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const {
auto _o = std::unique_ptr<WeaponT>(new WeaponT());
UnPackTo(_o.get(), _resolver);
return _o.release();
}
inline void Weapon::UnPackTo(WeaponT *_o, const ::flatbuffers::resolver_function_t *_resolver) const {
(void)_o;
(void)_resolver;
{ auto _e = name(); if (_e) _o->name = _e->str(); }
{ auto _e = damage(); _o->damage = _e; }
}
inline ::flatbuffers::Offset<Weapon> Weapon::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const WeaponT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) {
return CreateWeapon(_fbb, _o, _rehasher);
}
inline ::flatbuffers::Offset<Weapon> CreateWeapon(::flatbuffers::FlatBufferBuilder &_fbb, const WeaponT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) {
(void)_rehasher;
(void)_o;
struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const WeaponT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va;
auto _name = _o->name.empty() ? 0 : _fbb.CreateString(_o->name);
auto _damage = _o->damage;
return MyGame::Sample::CreateWeapon(
_fbb,
_name,
_damage);
}
inline bool VerifyEquipment(::flatbuffers::Verifier &verifier, const void *obj, Equipment type) {
switch (type) {
case Equipment_NONE: {
return true;
}
case Equipment_Weapon: {
auto ptr = reinterpret_cast<const MyGame::Sample::Weapon *>(obj);
return verifier.VerifyTable(ptr);
}
default: return true;
}
}
inline bool VerifyEquipmentVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset<void>> *values, const ::flatbuffers::Vector<uint8_t> *types) {
if (!values || !types) return !values && !types;
if (values->size() != types->size()) return false;
for (::flatbuffers::uoffset_t i = 0; i < values->size(); ++i) {
if (!VerifyEquipment(
verifier, values->Get(i), types->GetEnum<Equipment>(i))) {
return false;
}
}
return true;
}
inline void *EquipmentUnion::UnPack(const void *obj, Equipment type, const ::flatbuffers::resolver_function_t *resolver) {
(void)resolver;
switch (type) {
case Equipment_Weapon: {
auto ptr = reinterpret_cast<const MyGame::Sample::Weapon *>(obj);
return ptr->UnPack(resolver);
}
default: return nullptr;
}
}
inline ::flatbuffers::Offset<void> EquipmentUnion::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher) const {
(void)_rehasher;
switch (type) {
case Equipment_Weapon: {
auto ptr = reinterpret_cast<const MyGame::Sample::WeaponT *>(value);
return CreateWeapon(_fbb, ptr, _rehasher).Union();
}
default: return 0;
}
}
inline EquipmentUnion::EquipmentUnion(const EquipmentUnion &u) : type(u.type), value(nullptr) {
switch (type) {
case Equipment_Weapon: {
value = new MyGame::Sample::WeaponT(*reinterpret_cast<MyGame::Sample::WeaponT *>(u.value));
break;
}
default:
break;
}
}
inline void EquipmentUnion::Reset() {
switch (type) {
case Equipment_Weapon: {
auto ptr = reinterpret_cast<MyGame::Sample::WeaponT *>(value);
delete ptr;
break;
}
default: break;
}
value = nullptr;
type = Equipment_NONE;
}
inline const ::flatbuffers::TypeTable *ColorTypeTable() {
static const ::flatbuffers::TypeCode type_codes[] = {
{ ::flatbuffers::ET_CHAR, 0, 0 },
{ ::flatbuffers::ET_CHAR, 0, 0 },
{ ::flatbuffers::ET_CHAR, 0, 0 }
};
static const ::flatbuffers::TypeFunction type_refs[] = {
MyGame::Sample::ColorTypeTable
};
static const char * const names[] = {
"Red",
"Green",
"Blue"
};
static const ::flatbuffers::TypeTable tt = {
::flatbuffers::ST_ENUM, 3, type_codes, type_refs, nullptr, nullptr, names
};
return &tt;
}
inline const ::flatbuffers::TypeTable *EquipmentTypeTable() {
static const ::flatbuffers::TypeCode type_codes[] = {
{ ::flatbuffers::ET_SEQUENCE, 0, -1 },
{ ::flatbuffers::ET_SEQUENCE, 0, 0 }
};
static const ::flatbuffers::TypeFunction type_refs[] = {
MyGame::Sample::WeaponTypeTable
};
static const char * const names[] = {
"NONE",
"Weapon"
};
static const ::flatbuffers::TypeTable tt = {
::flatbuffers::ST_UNION, 2, type_codes, type_refs, nullptr, nullptr, names
};
return &tt;
}
inline const ::flatbuffers::TypeTable *Vec3TypeTable() {
static const ::flatbuffers::TypeCode type_codes[] = {
{ ::flatbuffers::ET_FLOAT, 0, -1 },
{ ::flatbuffers::ET_FLOAT, 0, -1 },
{ ::flatbuffers::ET_FLOAT, 0, -1 }
};
static const int64_t values[] = { 0, 4, 8, 12 };
static const char * const names[] = {
"x",
"y",
"z"
};
static const ::flatbuffers::TypeTable tt = {
::flatbuffers::ST_STRUCT, 3, type_codes, nullptr, nullptr, values, names
};
return &tt;
}
inline const ::flatbuffers::TypeTable *MonsterTypeTable() {
static const ::flatbuffers::TypeCode type_codes[] = {
{ ::flatbuffers::ET_SEQUENCE, 0, 0 },
{ ::flatbuffers::ET_SHORT, 0, -1 },
{ ::flatbuffers::ET_SHORT, 0, -1 },
{ ::flatbuffers::ET_STRING, 0, -1 },
{ ::flatbuffers::ET_BOOL, 0, -1 },
{ ::flatbuffers::ET_UCHAR, 1, -1 },
{ ::flatbuffers::ET_CHAR, 0, 1 },
{ ::flatbuffers::ET_SEQUENCE, 1, 2 },
{ ::flatbuffers::ET_UTYPE, 0, 3 },
{ ::flatbuffers::ET_SEQUENCE, 0, 3 },
{ ::flatbuffers::ET_SEQUENCE, 1, 0 }
};
static const ::flatbuffers::TypeFunction type_refs[] = {
MyGame::Sample::Vec3TypeTable,
MyGame::Sample::ColorTypeTable,
MyGame::Sample::WeaponTypeTable,
MyGame::Sample::EquipmentTypeTable
};
static const char * const names[] = {
"pos",
"mana",
"hp",
"name",
"friendly",
"inventory",
"color",
"weapons",
"equipped_type",
"equipped",
"path"
};
static const ::flatbuffers::TypeTable tt = {
::flatbuffers::ST_TABLE, 11, type_codes, type_refs, nullptr, nullptr, names
};
return &tt;
}
inline const ::flatbuffers::TypeTable *WeaponTypeTable() {
static const ::flatbuffers::TypeCode type_codes[] = {
{ ::flatbuffers::ET_STRING, 0, -1 },
{ ::flatbuffers::ET_SHORT, 0, -1 }
};
static const char * const names[] = {
"name",
"damage"
};
static const ::flatbuffers::TypeTable tt = {
::flatbuffers::ST_TABLE, 2, type_codes, nullptr, nullptr, nullptr, names
};
return &tt;
}
inline const MyGame::Sample::Monster *GetMonster(const void *buf) {
return ::flatbuffers::GetRoot<MyGame::Sample::Monster>(buf);
}
inline const MyGame::Sample::Monster *GetSizePrefixedMonster(const void *buf) {
return ::flatbuffers::GetSizePrefixedRoot<MyGame::Sample::Monster>(buf);
}
inline Monster *GetMutableMonster(void *buf) {
return ::flatbuffers::GetMutableRoot<Monster>(buf);
}
inline MyGame::Sample::Monster *GetMutableSizePrefixedMonster(void *buf) {
return ::flatbuffers::GetMutableSizePrefixedRoot<MyGame::Sample::Monster>(buf);
}
inline bool VerifyMonsterBuffer(
::flatbuffers::Verifier &verifier) {
return verifier.VerifyBuffer<MyGame::Sample::Monster>(nullptr);
}
inline bool VerifySizePrefixedMonsterBuffer(
::flatbuffers::Verifier &verifier) {
return verifier.VerifySizePrefixedBuffer<MyGame::Sample::Monster>(nullptr);
}
inline void FinishMonsterBuffer(
::flatbuffers::FlatBufferBuilder &fbb,
::flatbuffers::Offset<MyGame::Sample::Monster> root) {
fbb.Finish(root);
}
inline void FinishSizePrefixedMonsterBuffer(
::flatbuffers::FlatBufferBuilder &fbb,
::flatbuffers::Offset<MyGame::Sample::Monster> root) {
fbb.FinishSizePrefixed(root);
}
inline std::unique_ptr<MyGame::Sample::MonsterT> UnPackMonster(
const void *buf,
const ::flatbuffers::resolver_function_t *res = nullptr) {
return std::unique_ptr<MyGame::Sample::MonsterT>(GetMonster(buf)->UnPack(res));
}
inline std::unique_ptr<MyGame::Sample::MonsterT> UnPackSizePrefixedMonster(
const void *buf,
const ::flatbuffers::resolver_function_t *res = nullptr) {
return std::unique_ptr<MyGame::Sample::MonsterT>(GetSizePrefixedMonster(buf)->UnPack(res));
}
} // namespace Sample
} // namespace MyGame
#endif // FLATBUFFERS_GENERATED_MONSTER_MYGAME_SAMPLE_H_
@@ -0,0 +1,143 @@
// automatically generated by the FlatBuffers compiler, do not modify
import flatbuffers
namespace MyGame.Sample
enum Color:
Color_Red = 0
Color_Green = 1
Color_Blue = 2
enum Equipment:
Equipment_NONE = 0
Equipment_Weapon = 1
class Vec3
class Monster
class Weapon
class Vec3 : flatbuffers.handle
def x() -> float:
return buf_.read_float32_le(pos_ + 0)
def y() -> float:
return buf_.read_float32_le(pos_ + 4)
def z() -> float:
return buf_.read_float32_le(pos_ + 8)
def CreateVec3(b_:flatbuffers.builder, x:float, y:float, z:float):
b_.Prep(4, 12)
b_.PrependFloat32(z)
b_.PrependFloat32(y)
b_.PrependFloat32(x)
return b_.Offset()
class Monster : flatbuffers.handle
def pos() -> MyGame.Sample.Vec3?:
let o = flatbuffers.field_struct(buf_, pos_, 4)
return if o: MyGame.Sample.Vec3 { buf_, o } else: nil
def mana() -> int:
return flatbuffers.field_int16(buf_, pos_, 6, 150)
def hp() -> int:
return flatbuffers.field_int16(buf_, pos_, 8, 100)
def name() -> string:
return flatbuffers.field_string(buf_, pos_, 10)
def inventory(i:int) -> int:
return read_uint8_le(buf_, buf_.flatbuffers.field_vector(pos_, 14) + i * 1)
def inventory_length() -> int:
return flatbuffers.field_vector_len(buf_, pos_, 14)
def color() -> Color:
return Color(flatbuffers.field_int8(buf_, pos_, 16, 2))
def weapons(i:int) -> MyGame.Sample.Weapon:
return MyGame.Sample.Weapon { buf_, flatbuffers.indirect(buf_, flatbuffers.field_vector(buf_, pos_, 18) + i * 4) }
def weapons_length() -> int:
return flatbuffers.field_vector_len(buf_, pos_, 18)
def equipped_type() -> Equipment:
return Equipment(flatbuffers.field_uint8(buf_, pos_, 20, 0))
def equipped_as_Weapon():
return MyGame.Sample.Weapon { buf_, flatbuffers.field_table(buf_, pos_, 22) }
def path(i:int) -> MyGame.Sample.Vec3:
return MyGame.Sample.Vec3 { buf_, flatbuffers.field_vector(buf_, pos_, 24) + i * 12 }
def path_length() -> int:
return flatbuffers.field_vector_len(buf_, pos_, 24)
def GetRootAsMonster(buf:string): return Monster { buf, flatbuffers.indirect(buf, 0) }
struct MonsterBuilder:
b_:flatbuffers.builder
def start():
b_.StartObject(11)
return this
def add_pos(pos:flatbuffers.offset):
b_.PrependStructSlot(0, pos)
return this
def add_mana(mana:int):
b_.PrependInt16Slot(1, mana, 150)
return this
def add_hp(hp:int):
b_.PrependInt16Slot(2, hp, 100)
return this
def add_name(name:flatbuffers.offset):
b_.PrependUOffsetTRelativeSlot(3, name)
return this
def add_inventory(inventory:flatbuffers.offset):
b_.PrependUOffsetTRelativeSlot(5, inventory)
return this
def add_color(color:Color):
b_.PrependInt8Slot(6, color, 2)
return this
def add_weapons(weapons:flatbuffers.offset):
b_.PrependUOffsetTRelativeSlot(7, weapons)
return this
def add_equipped_type(equipped_type:Equipment):
b_.PrependUint8Slot(8, equipped_type, 0)
return this
def add_equipped(equipped:flatbuffers.offset):
b_.PrependUOffsetTRelativeSlot(9, equipped)
return this
def add_path(path:flatbuffers.offset):
b_.PrependUOffsetTRelativeSlot(10, path)
return this
def end():
return b_.EndObject()
def MonsterStartInventoryVector(b_:flatbuffers.builder, n_:int):
b_.StartVector(1, n_, 1)
def MonsterCreateInventoryVector(b_:flatbuffers.builder, v_:[int]):
b_.StartVector(1, v_.length, 1)
reverse(v_) e_: b_.PrependUint8(e_)
return b_.EndVector(v_.length)
def MonsterStartWeaponsVector(b_:flatbuffers.builder, n_:int):
b_.StartVector(4, n_, 4)
def MonsterCreateWeaponsVector(b_:flatbuffers.builder, v_:[flatbuffers.offset]):
b_.StartVector(4, v_.length, 4)
reverse(v_) e_: b_.PrependUOffsetTRelative(e_)
return b_.EndVector(v_.length)
def MonsterStartPathVector(b_:flatbuffers.builder, n_:int):
b_.StartVector(12, n_, 4)
class Weapon : flatbuffers.handle
def name() -> string:
return flatbuffers.field_string(buf_, pos_, 4)
def damage() -> int:
return flatbuffers.field_int16(buf_, pos_, 6, 0)
def GetRootAsWeapon(buf:string): return Weapon { buf, flatbuffers.indirect(buf, 0) }
struct WeaponBuilder:
b_:flatbuffers.builder
def start():
b_.StartObject(2)
return this
def add_name(name:flatbuffers.offset):
b_.PrependUOffsetTRelativeSlot(0, name)
return this
def add_damage(damage:int):
b_.PrependInt16Slot(1, damage, 0)
return this
def end():
return b_.EndObject()
+243
View File
@@ -0,0 +1,243 @@
// automatically generated by the FlatBuffers compiler, do not modify
// swiftlint:disable all
// swiftformat:disable all
import FlatBuffers
public enum MyGame_Sample_Color: Int8, Enum, Verifiable {
public typealias T = Int8
public static var byteSize: Int { return MemoryLayout<Int8>.size }
public var value: Int8 { return self.rawValue }
case red = 0
case green = 1
case blue = 2
public static var max: MyGame_Sample_Color { return .blue }
public static var min: MyGame_Sample_Color { return .red }
}
public enum MyGame_Sample_Equipment: UInt8, UnionEnum {
public typealias T = UInt8
public init?(value: T) {
self.init(rawValue: value)
}
public static var byteSize: Int { return MemoryLayout<UInt8>.size }
public var value: UInt8 { return self.rawValue }
case none_ = 0
case weapon = 1
public static var max: MyGame_Sample_Equipment { return .weapon }
public static var min: MyGame_Sample_Equipment { return .none_ }
}
public struct MyGame_Sample_Vec3: NativeStruct, Verifiable, FlatbuffersInitializable {
static func validateVersion() { FlatBuffersVersion_24_3_25() }
private var _x: Float32
private var _y: Float32
private var _z: Float32
public init(_ bb: ByteBuffer, o: Int32) {
let _accessor = Struct(bb: bb, position: o)
_x = _accessor.readBuffer(of: Float32.self, at: 0)
_y = _accessor.readBuffer(of: Float32.self, at: 4)
_z = _accessor.readBuffer(of: Float32.self, at: 8)
}
public init(x: Float32, y: Float32, z: Float32) {
_x = x
_y = y
_z = z
}
public init() {
_x = 0.0
_y = 0.0
_z = 0.0
}
public var x: Float32 { _x }
public var y: Float32 { _y }
public var z: Float32 { _z }
public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
try verifier.inBuffer(position: position, of: MyGame_Sample_Vec3.self)
}
}
public struct MyGame_Sample_Vec3_Mutable: FlatBufferObject {
static func validateVersion() { FlatBuffersVersion_24_3_25() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Struct
public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) }
public var x: Float32 { return _accessor.readBuffer(of: Float32.self, at: 0) }
@discardableResult public func mutate(x: Float32) -> Bool { return _accessor.mutate(x, index: 0) }
public var y: Float32 { return _accessor.readBuffer(of: Float32.self, at: 4) }
@discardableResult public func mutate(y: Float32) -> Bool { return _accessor.mutate(y, index: 4) }
public var z: Float32 { return _accessor.readBuffer(of: Float32.self, at: 8) }
@discardableResult public func mutate(z: Float32) -> Bool { return _accessor.mutate(z, index: 8) }
}
public struct MyGame_Sample_Monster: FlatBufferObject, Verifiable {
static func validateVersion() { FlatBuffersVersion_24_3_25() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table
private init(_ t: Table) { _accessor = t }
public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
private enum VTOFFSET: VOffset {
case pos = 4
case mana = 6
case hp = 8
case name = 10
case inventory = 14
case color = 16
case weapons = 18
case equippedType = 20
case equipped = 22
case path = 24
var v: Int32 { Int32(self.rawValue) }
var p: VOffset { self.rawValue }
}
public var pos: MyGame_Sample_Vec3? { let o = _accessor.offset(VTOFFSET.pos.v); return o == 0 ? nil : _accessor.readBuffer(of: MyGame_Sample_Vec3.self, at: o) }
public var mutablePos: MyGame_Sample_Vec3_Mutable? { let o = _accessor.offset(VTOFFSET.pos.v); return o == 0 ? nil : MyGame_Sample_Vec3_Mutable(_accessor.bb, o: o + _accessor.postion) }
public var mana: Int16 { let o = _accessor.offset(VTOFFSET.mana.v); return o == 0 ? 150 : _accessor.readBuffer(of: Int16.self, at: o) }
@discardableResult public func mutate(mana: Int16) -> Bool {let o = _accessor.offset(VTOFFSET.mana.v); return _accessor.mutate(mana, index: o) }
public var hp: Int16 { let o = _accessor.offset(VTOFFSET.hp.v); return o == 0 ? 100 : _accessor.readBuffer(of: Int16.self, at: o) }
@discardableResult public func mutate(hp: Int16) -> Bool {let o = _accessor.offset(VTOFFSET.hp.v); return _accessor.mutate(hp, index: o) }
public var name: String? { let o = _accessor.offset(VTOFFSET.name.v); return o == 0 ? nil : _accessor.string(at: o) }
public var nameSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.name.v) }
public var hasInventory: Bool { let o = _accessor.offset(VTOFFSET.inventory.v); return o == 0 ? false : true }
public var inventoryCount: Int32 { let o = _accessor.offset(VTOFFSET.inventory.v); return o == 0 ? 0 : _accessor.vector(count: o) }
public func inventory(at index: Int32) -> UInt8 { let o = _accessor.offset(VTOFFSET.inventory.v); return o == 0 ? 0 : _accessor.directRead(of: UInt8.self, offset: _accessor.vector(at: o) + index * 1) }
public var inventory: [UInt8] { return _accessor.getVector(at: VTOFFSET.inventory.v) ?? [] }
public func mutate(inventory: UInt8, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.inventory.v); return _accessor.directMutate(inventory, index: _accessor.vector(at: o) + index * 1) }
public var color: MyGame_Sample_Color { let o = _accessor.offset(VTOFFSET.color.v); return o == 0 ? .blue : MyGame_Sample_Color(rawValue: _accessor.readBuffer(of: Int8.self, at: o)) ?? .blue }
@discardableResult public func mutate(color: MyGame_Sample_Color) -> Bool {let o = _accessor.offset(VTOFFSET.color.v); return _accessor.mutate(color.rawValue, index: o) }
public var hasWeapons: Bool { let o = _accessor.offset(VTOFFSET.weapons.v); return o == 0 ? false : true }
public var weaponsCount: Int32 { let o = _accessor.offset(VTOFFSET.weapons.v); return o == 0 ? 0 : _accessor.vector(count: o) }
public func weapons(at index: Int32) -> MyGame_Sample_Weapon? { let o = _accessor.offset(VTOFFSET.weapons.v); return o == 0 ? nil : MyGame_Sample_Weapon(_accessor.bb, o: _accessor.indirect(_accessor.vector(at: o) + index * 4)) }
public var equippedType: MyGame_Sample_Equipment { let o = _accessor.offset(VTOFFSET.equippedType.v); return o == 0 ? .none_ : MyGame_Sample_Equipment(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .none_ }
public func equipped<T: FlatbuffersInitializable>(type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.equipped.v); return o == 0 ? nil : _accessor.union(o) }
public var hasPath: Bool { let o = _accessor.offset(VTOFFSET.path.v); return o == 0 ? false : true }
public var pathCount: Int32 { let o = _accessor.offset(VTOFFSET.path.v); return o == 0 ? 0 : _accessor.vector(count: o) }
public func path(at index: Int32) -> MyGame_Sample_Vec3? { let o = _accessor.offset(VTOFFSET.path.v); return o == 0 ? nil : _accessor.directRead(of: MyGame_Sample_Vec3.self, offset: _accessor.vector(at: o) + index * 12) }
public func mutablePath(at index: Int32) -> MyGame_Sample_Vec3_Mutable? { let o = _accessor.offset(VTOFFSET.path.v); return o == 0 ? nil : MyGame_Sample_Vec3_Mutable(_accessor.bb, o: _accessor.vector(at: o) + index * 12) }
public static func startMonster(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 11) }
public static func add(pos: MyGame_Sample_Vec3?, _ fbb: inout FlatBufferBuilder) { guard let pos = pos else { return }; fbb.create(struct: pos, position: VTOFFSET.pos.p) }
public static func add(mana: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: mana, def: 150, at: VTOFFSET.mana.p) }
public static func add(hp: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: hp, def: 100, at: VTOFFSET.hp.p) }
public static func add(name: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VTOFFSET.name.p) }
public static func addVectorOf(inventory: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: inventory, at: VTOFFSET.inventory.p) }
public static func add(color: MyGame_Sample_Color, _ fbb: inout FlatBufferBuilder) { fbb.add(element: color.rawValue, def: 2, at: VTOFFSET.color.p) }
public static func addVectorOf(weapons: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: weapons, at: VTOFFSET.weapons.p) }
public static func add(equippedType: MyGame_Sample_Equipment, _ fbb: inout FlatBufferBuilder) { fbb.add(element: equippedType.rawValue, def: 0, at: VTOFFSET.equippedType.p) }
public static func add(equipped: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: equipped, at: VTOFFSET.equipped.p) }
public static func addVectorOf(path: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: path, at: VTOFFSET.path.p) }
public static func startVectorOfPath(_ size: Int, in builder: inout FlatBufferBuilder) {
builder.startVector(size * MemoryLayout<MyGame_Sample_Vec3>.size, elementSize: MemoryLayout<MyGame_Sample_Vec3>.alignment)
}
public static func endMonster(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end }
public static func createMonster(
_ fbb: inout FlatBufferBuilder,
pos: MyGame_Sample_Vec3? = nil,
mana: Int16 = 150,
hp: Int16 = 100,
nameOffset name: Offset = Offset(),
inventoryVectorOffset inventory: Offset = Offset(),
color: MyGame_Sample_Color = .blue,
weaponsVectorOffset weapons: Offset = Offset(),
equippedType: MyGame_Sample_Equipment = .none_,
equippedOffset equipped: Offset = Offset(),
pathVectorOffset path: Offset = Offset()
) -> Offset {
let __start = MyGame_Sample_Monster.startMonster(&fbb)
MyGame_Sample_Monster.add(pos: pos, &fbb)
MyGame_Sample_Monster.add(mana: mana, &fbb)
MyGame_Sample_Monster.add(hp: hp, &fbb)
MyGame_Sample_Monster.add(name: name, &fbb)
MyGame_Sample_Monster.addVectorOf(inventory: inventory, &fbb)
MyGame_Sample_Monster.add(color: color, &fbb)
MyGame_Sample_Monster.addVectorOf(weapons: weapons, &fbb)
MyGame_Sample_Monster.add(equippedType: equippedType, &fbb)
MyGame_Sample_Monster.add(equipped: equipped, &fbb)
MyGame_Sample_Monster.addVectorOf(path: path, &fbb)
return MyGame_Sample_Monster.endMonster(&fbb, start: __start)
}
public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
var _v = try verifier.visitTable(at: position)
try _v.visit(field: VTOFFSET.pos.p, fieldName: "pos", required: false, type: MyGame_Sample_Vec3.self)
try _v.visit(field: VTOFFSET.mana.p, fieldName: "mana", required: false, type: Int16.self)
try _v.visit(field: VTOFFSET.hp.p, fieldName: "hp", required: false, type: Int16.self)
try _v.visit(field: VTOFFSET.name.p, fieldName: "name", required: false, type: ForwardOffset<String>.self)
try _v.visit(field: VTOFFSET.inventory.p, fieldName: "inventory", required: false, type: ForwardOffset<Vector<UInt8, UInt8>>.self)
try _v.visit(field: VTOFFSET.color.p, fieldName: "color", required: false, type: MyGame_Sample_Color.self)
try _v.visit(field: VTOFFSET.weapons.p, fieldName: "weapons", required: false, type: ForwardOffset<Vector<ForwardOffset<MyGame_Sample_Weapon>, MyGame_Sample_Weapon>>.self)
try _v.visit(unionKey: VTOFFSET.equippedType.p, unionField: VTOFFSET.equipped.p, unionKeyName: "equippedType", fieldName: "equipped", required: false, completion: { (verifier, key: MyGame_Sample_Equipment, pos) in
switch key {
case .none_:
break // NOTE - SWIFT doesnt support none
case .weapon:
try ForwardOffset<MyGame_Sample_Weapon>.verify(&verifier, at: pos, of: MyGame_Sample_Weapon.self)
}
})
try _v.visit(field: VTOFFSET.path.p, fieldName: "path", required: false, type: ForwardOffset<Vector<MyGame_Sample_Vec3, MyGame_Sample_Vec3>>.self)
_v.finish()
}
}
public struct MyGame_Sample_Weapon: FlatBufferObject, Verifiable {
static func validateVersion() { FlatBuffersVersion_24_3_25() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table
private init(_ t: Table) { _accessor = t }
public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
private enum VTOFFSET: VOffset {
case name = 4
case damage = 6
var v: Int32 { Int32(self.rawValue) }
var p: VOffset { self.rawValue }
}
public var name: String? { let o = _accessor.offset(VTOFFSET.name.v); return o == 0 ? nil : _accessor.string(at: o) }
public var nameSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.name.v) }
public var damage: Int16 { let o = _accessor.offset(VTOFFSET.damage.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int16.self, at: o) }
@discardableResult public func mutate(damage: Int16) -> Bool {let o = _accessor.offset(VTOFFSET.damage.v); return _accessor.mutate(damage, index: o) }
public static func startWeapon(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 2) }
public static func add(name: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VTOFFSET.name.p) }
public static func add(damage: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: damage, def: 0, at: VTOFFSET.damage.p) }
public static func endWeapon(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end }
public static func createWeapon(
_ fbb: inout FlatBufferBuilder,
nameOffset name: Offset = Offset(),
damage: Int16 = 0
) -> Offset {
let __start = MyGame_Sample_Weapon.startWeapon(&fbb)
MyGame_Sample_Weapon.add(name: name, &fbb)
MyGame_Sample_Weapon.add(damage: damage, &fbb)
return MyGame_Sample_Weapon.endWeapon(&fbb, start: __start)
}
public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
var _v = try verifier.visitTable(at: position)
try _v.visit(field: VTOFFSET.name.p, fieldName: "name", required: false, type: ForwardOffset<String>.self)
try _v.visit(field: VTOFFSET.damage.p, fieldName: "damage", required: false, type: Int16.self)
_v.finish()
}
}
+24
View File
@@ -0,0 +1,24 @@
{
"pos": {
"x": 1.0,
"y": 2.0,
"z": 3.0
},
"hp": 300,
"name": "Orc",
"weapons": [
{
"name": "axe",
"damage": 100
},
{
"name": "bow",
"damage": 90
}
],
"equipped_type": "Weapon",
"equipped": {
"name": "bow",
"damage": 90
}
}
+48
View File
@@ -0,0 +1,48 @@
#!/bin/bash
#
# Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Note: This script runs on Mac and Linux. It requires `php` to be installed
# and `flatc` to be built (using `cmake` in the root directory).
sampledir=$(cd $(dirname $BASH_SOURCE) && pwd)
rootdir=$(cd $sampledir/.. && pwd)
currentdir=$(pwd)
if [[ "$sampledir" != "$currentdir" ]]; then
echo Error: This script must be run from inside the $sampledir directory.
echo You executed it from the $currentdir directory.
exit 1
fi
# Run `flatc`. Note: This requires you to compile using `cmake` from the
# root `/flatbuffers` directory.
if [ -e ../flatc ]; then
../flatc --php monster.fbs
elif [ -e ../Debug/flatc ]; then
../Debug/flatc --php monster.fbs
else
echo 'flatc' could not be found. Make sure to build FlatBuffers from the \
$rootdir directory.
exit 1
fi
echo Running the PHP sample.
# Execute the sample.
php SampleBinary.php
# Clean up temporary files.
rm -rf MyGame/
+48
View File
@@ -0,0 +1,48 @@
#!/bin/bash
#
# Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Note: This script runs on Mac and Linux. It requires `python` to be installed
# and `flatc` to be built (using `cmake` in the root directory).
sampledir=$(cd $(dirname $BASH_SOURCE) && pwd)
rootdir=$(cd $sampledir/.. && pwd)
currentdir=$(pwd)
if [[ "$sampledir" != "$currentdir" ]]; then
echo Error: This script must be run from inside the $sampledir directory.
echo You executed it from the $currentdir directory.
exit 1
fi
# Run `flatc`. Note: This requires you to compile using `cmake` from the
# root `/flatbuffers` directory.
if [ -e ../flatc ]; then
../flatc --python monster.fbs
elif [ -e ../Debug/flatc ]; then
../Debug/flatc --python monster.fbs
else
echo 'flatc' could not be found. Make sure to build FlatBuffers from the \
$rootdir directory.
exit 1
fi
echo Running the Python sample.
# Execute the sample.
python sample_binary.py
# Clean up the temporary files.
rm -rf MyGame
+18
View File
@@ -0,0 +1,18 @@
// Automatically generated by the Flatbuffers compiler. Do not modify.
// @generated
pub mod my_game {
use super::*;
pub mod sample {
use super::*;
mod color_generated;
pub use self::color_generated::*;
mod equipment_generated;
pub use self::equipment_generated::*;
mod vec_3_generated;
pub use self::vec_3_generated::*;
mod monster_generated;
pub use self::monster_generated::*;
mod weapon_generated;
pub use self::weapon_generated::*;
} // sample
} // my_game
@@ -0,0 +1,100 @@
// automatically generated by the FlatBuffers compiler, do not modify
// @generated
extern crate alloc;
extern crate flatbuffers;
use alloc::boxed::Box;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::mem;
use core::cmp::Ordering;
use self::flatbuffers::{EndianScalar, Follow};
use super::*;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
pub const ENUM_MIN_COLOR: i8 = 0;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
pub const ENUM_MAX_COLOR: i8 = 2;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
#[allow(non_camel_case_types)]
pub const ENUM_VALUES_COLOR: [Color; 3] = [
Color::Red,
Color::Green,
Color::Blue,
];
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[repr(transparent)]
pub struct Color(pub i8);
#[allow(non_upper_case_globals)]
impl Color {
pub const Red: Self = Self(0);
pub const Green: Self = Self(1);
pub const Blue: Self = Self(2);
pub const ENUM_MIN: i8 = 0;
pub const ENUM_MAX: i8 = 2;
pub const ENUM_VALUES: &'static [Self] = &[
Self::Red,
Self::Green,
Self::Blue,
];
/// Returns the variant's name or "" if unknown.
pub fn variant_name(self) -> Option<&'static str> {
match self {
Self::Red => Some("Red"),
Self::Green => Some("Green"),
Self::Blue => Some("Blue"),
_ => None,
}
}
}
impl core::fmt::Debug for Color {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
if let Some(name) = self.variant_name() {
f.write_str(name)
} else {
f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
}
}
}
impl<'a> flatbuffers::Follow<'a> for Color {
type Inner = Self;
#[inline]
unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
let b = flatbuffers::read_scalar_at::<i8>(buf, loc);
Self(b)
}
}
impl flatbuffers::Push for Color {
type Output = Color;
#[inline]
unsafe fn push(&self, dst: &mut [u8], _written_len: usize) {
flatbuffers::emplace_scalar::<i8>(dst, self.0);
}
}
impl flatbuffers::EndianScalar for Color {
type Scalar = i8;
#[inline]
fn to_little_endian(self) -> i8 {
self.0.to_le()
}
#[inline]
#[allow(clippy::wrong_self_convention)]
fn from_little_endian(v: i8) -> Self {
let b = i8::from_le(v);
Self(b)
}
}
impl<'a> flatbuffers::Verifiable for Color {
#[inline]
fn run_verifier(
v: &mut flatbuffers::Verifier, pos: usize
) -> Result<(), flatbuffers::InvalidFlatbuffer> {
use self::flatbuffers::Verifiable;
i8::run_verifier(v, pos)
}
}
impl flatbuffers::SimpleToVerifyInSlice for Color {}
@@ -0,0 +1,145 @@
// automatically generated by the FlatBuffers compiler, do not modify
// @generated
extern crate alloc;
extern crate flatbuffers;
use alloc::boxed::Box;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::mem;
use core::cmp::Ordering;
use self::flatbuffers::{EndianScalar, Follow};
use super::*;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
pub const ENUM_MIN_EQUIPMENT: u8 = 0;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
pub const ENUM_MAX_EQUIPMENT: u8 = 1;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
#[allow(non_camel_case_types)]
pub const ENUM_VALUES_EQUIPMENT: [Equipment; 2] = [
Equipment::NONE,
Equipment::Weapon,
];
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[repr(transparent)]
pub struct Equipment(pub u8);
#[allow(non_upper_case_globals)]
impl Equipment {
pub const NONE: Self = Self(0);
pub const Weapon: Self = Self(1);
pub const ENUM_MIN: u8 = 0;
pub const ENUM_MAX: u8 = 1;
pub const ENUM_VALUES: &'static [Self] = &[
Self::NONE,
Self::Weapon,
];
/// Returns the variant's name or "" if unknown.
pub fn variant_name(self) -> Option<&'static str> {
match self {
Self::NONE => Some("NONE"),
Self::Weapon => Some("Weapon"),
_ => None,
}
}
}
impl core::fmt::Debug for Equipment {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
if let Some(name) = self.variant_name() {
f.write_str(name)
} else {
f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
}
}
}
impl<'a> flatbuffers::Follow<'a> for Equipment {
type Inner = Self;
#[inline]
unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
let b = flatbuffers::read_scalar_at::<u8>(buf, loc);
Self(b)
}
}
impl flatbuffers::Push for Equipment {
type Output = Equipment;
#[inline]
unsafe fn push(&self, dst: &mut [u8], _written_len: usize) {
flatbuffers::emplace_scalar::<u8>(dst, self.0);
}
}
impl flatbuffers::EndianScalar for Equipment {
type Scalar = u8;
#[inline]
fn to_little_endian(self) -> u8 {
self.0.to_le()
}
#[inline]
#[allow(clippy::wrong_self_convention)]
fn from_little_endian(v: u8) -> Self {
let b = u8::from_le(v);
Self(b)
}
}
impl<'a> flatbuffers::Verifiable for Equipment {
#[inline]
fn run_verifier(
v: &mut flatbuffers::Verifier, pos: usize
) -> Result<(), flatbuffers::InvalidFlatbuffer> {
use self::flatbuffers::Verifiable;
u8::run_verifier(v, pos)
}
}
impl flatbuffers::SimpleToVerifyInSlice for Equipment {}
pub struct EquipmentUnionTableOffset {}
#[allow(clippy::upper_case_acronyms)]
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub enum EquipmentT {
NONE,
Weapon(Box<WeaponT>),
}
impl Default for EquipmentT {
fn default() -> Self {
Self::NONE
}
}
impl EquipmentT {
pub fn equipment_type(&self) -> Equipment {
match self {
Self::NONE => Equipment::NONE,
Self::Weapon(_) => Equipment::Weapon,
}
}
pub fn pack<'b, A: flatbuffers::Allocator + 'b>(&self, fbb: &mut flatbuffers::FlatBufferBuilder<'b, A>) -> Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>> {
match self {
Self::NONE => None,
Self::Weapon(v) => Some(v.pack(fbb).as_union_value()),
}
}
/// If the union variant matches, return the owned WeaponT, setting the union to NONE.
pub fn take_weapon(&mut self) -> Option<Box<WeaponT>> {
if let Self::Weapon(_) = self {
let v = core::mem::replace(self, Self::NONE);
if let Self::Weapon(w) = v {
Some(w)
} else {
unreachable!()
}
} else {
None
}
}
/// If the union variant matches, return a reference to the WeaponT.
pub fn as_weapon(&self) -> Option<&WeaponT> {
if let Self::Weapon(v) = self { Some(v.as_ref()) } else { None }
}
/// If the union variant matches, return a mutable reference to the WeaponT.
pub fn as_weapon_mut(&mut self) -> Option<&mut WeaponT> {
if let Self::Weapon(v) = self { Some(v.as_mut()) } else { None }
}
}
@@ -0,0 +1,473 @@
// automatically generated by the FlatBuffers compiler, do not modify
// @generated
extern crate alloc;
extern crate flatbuffers;
use alloc::boxed::Box;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::mem;
use core::cmp::Ordering;
use self::flatbuffers::{EndianScalar, Follow};
use super::*;
pub enum MonsterOffset {}
#[derive(Copy, Clone, PartialEq)]
pub struct Monster<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for Monster<'a> {
type Inner = Monster<'a>;
#[inline]
unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self { _tab: flatbuffers::Table::new(buf, loc) }
}
}
impl<'a> Monster<'a> {
pub const VT_POS: flatbuffers::VOffsetT = 4;
pub const VT_MANA: flatbuffers::VOffsetT = 6;
pub const VT_HP: flatbuffers::VOffsetT = 8;
pub const VT_NAME: flatbuffers::VOffsetT = 10;
pub const VT_INVENTORY: flatbuffers::VOffsetT = 14;
pub const VT_COLOR: flatbuffers::VOffsetT = 16;
pub const VT_WEAPONS: flatbuffers::VOffsetT = 18;
pub const VT_EQUIPPED_TYPE: flatbuffers::VOffsetT = 20;
pub const VT_EQUIPPED: flatbuffers::VOffsetT = 22;
pub const VT_PATH: flatbuffers::VOffsetT = 24;
pub const fn get_fully_qualified_name() -> &'static str {
"MyGame.Sample.Monster"
}
#[inline]
pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
Monster { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>,
args: &'args MonsterArgs<'args>
) -> flatbuffers::WIPOffset<Monster<'bldr>> {
let mut builder = MonsterBuilder::new(_fbb);
if let Some(x) = args.path { builder.add_path(x); }
if let Some(x) = args.equipped { builder.add_equipped(x); }
if let Some(x) = args.weapons { builder.add_weapons(x); }
if let Some(x) = args.inventory { builder.add_inventory(x); }
if let Some(x) = args.name { builder.add_name(x); }
if let Some(x) = args.pos { builder.add_pos(x); }
builder.add_hp(args.hp);
builder.add_mana(args.mana);
builder.add_equipped_type(args.equipped_type);
builder.add_color(args.color);
builder.finish()
}
pub fn unpack(&self) -> MonsterT {
let pos = self.pos().map(|x| {
x.unpack()
});
let mana = self.mana();
let hp = self.hp();
let name = self.name().map(|x| {
x.to_string()
});
let inventory = self.inventory().map(|x| {
x.into_iter().collect()
});
let color = self.color();
let weapons = self.weapons().map(|x| {
x.iter().map(|t| t.unpack()).collect()
});
let equipped = match self.equipped_type() {
Equipment::NONE => EquipmentT::NONE,
Equipment::Weapon => EquipmentT::Weapon(Box::new(
self.equipped_as_weapon()
.expect("Invalid union table, expected `Equipment::Weapon`.")
.unpack()
)),
_ => EquipmentT::NONE,
};
let path = self.path().map(|x| {
x.iter().map(|t| t.unpack()).collect()
});
MonsterT {
pos,
mana,
hp,
name,
inventory,
color,
weapons,
equipped,
path,
}
}
#[inline]
pub fn pos(&self) -> Option<&'a Vec3> {
// Safety:
// Created from valid Table for this object
// which contains a valid value in this slot
unsafe { self._tab.get::<Vec3>(Monster::VT_POS, None)}
}
#[inline]
pub fn mana(&self) -> i16 {
// Safety:
// Created from valid Table for this object
// which contains a valid value in this slot
unsafe { self._tab.get::<i16>(Monster::VT_MANA, Some(150)).unwrap()}
}
#[inline]
pub fn hp(&self) -> i16 {
// Safety:
// Created from valid Table for this object
// which contains a valid value in this slot
unsafe { self._tab.get::<i16>(Monster::VT_HP, Some(100)).unwrap()}
}
#[inline]
pub fn name(&self) -> Option<&'a str> {
// Safety:
// Created from valid Table for this object
// which contains a valid value in this slot
unsafe { self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(Monster::VT_NAME, None)}
}
#[inline]
pub fn inventory(&self) -> Option<flatbuffers::Vector<'a, u8>> {
// Safety:
// Created from valid Table for this object
// which contains a valid value in this slot
unsafe { self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, u8>>>(Monster::VT_INVENTORY, None)}
}
#[inline]
pub fn color(&self) -> Color {
// Safety:
// Created from valid Table for this object
// which contains a valid value in this slot
unsafe { self._tab.get::<Color>(Monster::VT_COLOR, Some(Color::Blue)).unwrap()}
}
#[inline]
pub fn weapons(&self) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Weapon<'a>>>> {
// Safety:
// Created from valid Table for this object
// which contains a valid value in this slot
unsafe { self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Weapon>>>>(Monster::VT_WEAPONS, None)}
}
#[inline]
pub fn equipped_type(&self) -> Equipment {
// Safety:
// Created from valid Table for this object
// which contains a valid value in this slot
unsafe { self._tab.get::<Equipment>(Monster::VT_EQUIPPED_TYPE, Some(Equipment::NONE)).unwrap()}
}
#[inline]
pub fn equipped(&self) -> Option<flatbuffers::Table<'a>> {
// Safety:
// Created from valid Table for this object
// which contains a valid value in this slot
unsafe { self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(Monster::VT_EQUIPPED, None)}
}
#[inline]
pub fn path(&self) -> Option<flatbuffers::Vector<'a, Vec3>> {
// Safety:
// Created from valid Table for this object
// which contains a valid value in this slot
unsafe { self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, Vec3>>>(Monster::VT_PATH, None)}
}
#[inline]
#[allow(non_snake_case)]
pub fn equipped_as_weapon(&self) -> Option<Weapon<'a>> {
if self.equipped_type() == Equipment::Weapon {
self.equipped().map(|t| {
// Safety:
// Created from a valid Table for this object
// Which contains a valid union in this slot
unsafe { Weapon::init_from_table(t) }
})
} else {
None
}
}
}
impl flatbuffers::Verifiable for Monster<'_> {
#[inline]
fn run_verifier(
v: &mut flatbuffers::Verifier, pos: usize
) -> Result<(), flatbuffers::InvalidFlatbuffer> {
use self::flatbuffers::Verifiable;
v.visit_table(pos)?
.visit_field::<Vec3>("pos", Self::VT_POS, false)?
.visit_field::<i16>("mana", Self::VT_MANA, false)?
.visit_field::<i16>("hp", Self::VT_HP, false)?
.visit_field::<flatbuffers::ForwardsUOffset<&str>>("name", Self::VT_NAME, false)?
.visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, u8>>>("inventory", Self::VT_INVENTORY, false)?
.visit_field::<Color>("color", Self::VT_COLOR, false)?
.visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, flatbuffers::ForwardsUOffset<Weapon>>>>("weapons", Self::VT_WEAPONS, false)?
.visit_union::<Equipment, _>("equipped_type", Self::VT_EQUIPPED_TYPE, "equipped", Self::VT_EQUIPPED, false, |key, v, pos| {
match key {
Equipment::Weapon => v.verify_union_variant::<flatbuffers::ForwardsUOffset<Weapon>>("Equipment::Weapon", pos),
_ => Ok(()),
}
})?
.visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, Vec3>>>("path", Self::VT_PATH, false)?
.finish();
Ok(())
}
}
pub struct MonsterArgs<'a> {
pub pos: Option<&'a Vec3>,
pub mana: i16,
pub hp: i16,
pub name: Option<flatbuffers::WIPOffset<&'a str>>,
pub inventory: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, u8>>>,
pub color: Color,
pub weapons: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Weapon<'a>>>>>,
pub equipped_type: Equipment,
pub equipped: Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>,
pub path: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, Vec3>>>,
}
impl<'a> Default for MonsterArgs<'a> {
#[inline]
fn default() -> Self {
MonsterArgs {
pos: None,
mana: 150,
hp: 100,
name: None,
inventory: None,
color: Color::Blue,
weapons: None,
equipped_type: Equipment::NONE,
equipped: None,
path: None,
}
}
}
pub struct MonsterBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> MonsterBuilder<'a, 'b, A> {
#[inline]
pub fn add_pos(&mut self, pos: &Vec3) {
self.fbb_.push_slot_always::<&Vec3>(Monster::VT_POS, pos);
}
#[inline]
pub fn add_mana(&mut self, mana: i16) {
self.fbb_.push_slot::<i16>(Monster::VT_MANA, mana, 150);
}
#[inline]
pub fn add_hp(&mut self, hp: i16) {
self.fbb_.push_slot::<i16>(Monster::VT_HP, hp, 100);
}
#[inline]
pub fn add_name(&mut self, name: flatbuffers::WIPOffset<&'b str>) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_NAME, name);
}
#[inline]
pub fn add_inventory(&mut self, inventory: flatbuffers::WIPOffset<flatbuffers::Vector<'b , u8>>) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_INVENTORY, inventory);
}
#[inline]
pub fn add_color(&mut self, color: Color) {
self.fbb_.push_slot::<Color>(Monster::VT_COLOR, color, Color::Blue);
}
#[inline]
pub fn add_weapons(&mut self, weapons: flatbuffers::WIPOffset<flatbuffers::Vector<'b , flatbuffers::ForwardsUOffset<Weapon<'b >>>>) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_WEAPONS, weapons);
}
#[inline]
pub fn add_equipped_type(&mut self, equipped_type: Equipment) {
self.fbb_.push_slot::<Equipment>(Monster::VT_EQUIPPED_TYPE, equipped_type, Equipment::NONE);
}
#[inline]
pub fn add_equipped(&mut self, equipped: flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_EQUIPPED, equipped);
}
#[inline]
pub fn add_path(&mut self, path: flatbuffers::WIPOffset<flatbuffers::Vector<'b , Vec3>>) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Monster::VT_PATH, path);
}
#[inline]
pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> MonsterBuilder<'a, 'b, A> {
let start = _fbb.start_table();
MonsterBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<Monster<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
impl core::fmt::Debug for Monster<'_> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let mut ds = f.debug_struct("Monster");
ds.field("pos", &self.pos());
ds.field("mana", &self.mana());
ds.field("hp", &self.hp());
ds.field("name", &self.name());
ds.field("inventory", &self.inventory());
ds.field("color", &self.color());
ds.field("weapons", &self.weapons());
ds.field("equipped_type", &self.equipped_type());
match self.equipped_type() {
Equipment::Weapon => {
if let Some(x) = self.equipped_as_weapon() {
ds.field("equipped", &x)
} else {
ds.field("equipped", &"InvalidFlatbuffer: Union discriminant does not match value.")
}
},
_ => {
let x: Option<()> = None;
ds.field("equipped", &x)
},
};
ds.field("path", &self.path());
ds.finish()
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub struct MonsterT {
pub pos: Option<Vec3T>,
pub mana: i16,
pub hp: i16,
pub name: Option<String>,
pub inventory: Option<Vec<u8>>,
pub color: Color,
pub weapons: Option<Vec<WeaponT>>,
pub equipped: EquipmentT,
pub path: Option<Vec<Vec3T>>,
}
impl Default for MonsterT {
fn default() -> Self {
Self {
pos: None,
mana: 150,
hp: 100,
name: None,
inventory: None,
color: Color::Blue,
weapons: None,
equipped: EquipmentT::NONE,
path: None,
}
}
}
impl MonsterT {
pub fn pack<'b, A: flatbuffers::Allocator + 'b>(
&self,
_fbb: &mut flatbuffers::FlatBufferBuilder<'b, A>
) -> flatbuffers::WIPOffset<Monster<'b>> {
let pos_tmp = self.pos.as_ref().map(|x| x.pack());
let pos = pos_tmp.as_ref();
let mana = self.mana;
let hp = self.hp;
let name = self.name.as_ref().map(|x|{
_fbb.create_string(x)
});
let inventory = self.inventory.as_ref().map(|x|{
_fbb.create_vector(x)
});
let color = self.color;
let weapons = self.weapons.as_ref().map(|x|{
let w: Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w)
});
let equipped_type = self.equipped.equipment_type();
let equipped = self.equipped.pack(_fbb);
let path = self.path.as_ref().map(|x|{
let w: Vec<_> = x.iter().map(|t| t.pack()).collect();_fbb.create_vector(&w)
});
Monster::create(_fbb, &MonsterArgs{
pos,
mana,
hp,
name,
inventory,
color,
weapons,
equipped_type,
equipped,
path,
})
}
}
#[inline]
/// Verifies that a buffer of bytes contains a `Monster`
/// and returns it.
/// Note that verification is still experimental and may not
/// catch every error, or be maximally performant. For the
/// previous, unchecked, behavior use
/// `root_as_monster_unchecked`.
pub fn root_as_monster(buf: &[u8]) -> Result<Monster, flatbuffers::InvalidFlatbuffer> {
flatbuffers::root::<Monster>(buf)
}
#[inline]
/// Verifies that a buffer of bytes contains a size prefixed
/// `Monster` and returns it.
/// Note that verification is still experimental and may not
/// catch every error, or be maximally performant. For the
/// previous, unchecked, behavior use
/// `size_prefixed_root_as_monster_unchecked`.
pub fn size_prefixed_root_as_monster(buf: &[u8]) -> Result<Monster, flatbuffers::InvalidFlatbuffer> {
flatbuffers::size_prefixed_root::<Monster>(buf)
}
#[inline]
/// Verifies, with the given options, that a buffer of bytes
/// contains a `Monster` and returns it.
/// Note that verification is still experimental and may not
/// catch every error, or be maximally performant. For the
/// previous, unchecked, behavior use
/// `root_as_monster_unchecked`.
pub fn root_as_monster_with_opts<'b, 'o>(
opts: &'o flatbuffers::VerifierOptions,
buf: &'b [u8],
) -> Result<Monster<'b>, flatbuffers::InvalidFlatbuffer> {
flatbuffers::root_with_opts::<Monster<'b>>(opts, buf)
}
#[inline]
/// Verifies, with the given verifier options, that a buffer of
/// bytes contains a size prefixed `Monster` and returns
/// it. Note that verification is still experimental and may not
/// catch every error, or be maximally performant. For the
/// previous, unchecked, behavior use
/// `root_as_monster_unchecked`.
pub fn size_prefixed_root_as_monster_with_opts<'b, 'o>(
opts: &'o flatbuffers::VerifierOptions,
buf: &'b [u8],
) -> Result<Monster<'b>, flatbuffers::InvalidFlatbuffer> {
flatbuffers::size_prefixed_root_with_opts::<Monster<'b>>(opts, buf)
}
#[inline]
/// Assumes, without verification, that a buffer of bytes contains a Monster and returns it.
/// # Safety
/// Callers must trust the given bytes do indeed contain a valid `Monster`.
pub unsafe fn root_as_monster_unchecked(buf: &[u8]) -> Monster {
flatbuffers::root_unchecked::<Monster>(buf)
}
#[inline]
/// Assumes, without verification, that a buffer of bytes contains a size prefixed Monster and returns it.
/// # Safety
/// Callers must trust the given bytes do indeed contain a valid size prefixed `Monster`.
pub unsafe fn size_prefixed_root_as_monster_unchecked(buf: &[u8]) -> Monster {
flatbuffers::size_prefixed_root_unchecked::<Monster>(buf)
}
#[inline]
pub fn finish_monster_buffer<'a, 'b, A: flatbuffers::Allocator + 'a>(
fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>,
root: flatbuffers::WIPOffset<Monster<'a>>) {
fbb.finish(root, None);
}
#[inline]
pub fn finish_size_prefixed_monster_buffer<'a, 'b, A: flatbuffers::Allocator + 'a>(fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, root: flatbuffers::WIPOffset<Monster<'a>>) {
fbb.finish_size_prefixed(root, None);
}
@@ -0,0 +1,194 @@
// automatically generated by the FlatBuffers compiler, do not modify
// @generated
extern crate alloc;
extern crate flatbuffers;
use alloc::boxed::Box;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::mem;
use core::cmp::Ordering;
use self::flatbuffers::{EndianScalar, Follow};
use super::*;
// struct Vec3, aligned to 4
#[repr(transparent)]
#[derive(Clone, Copy, PartialEq)]
pub struct Vec3(pub [u8; 12]);
impl Default for Vec3 {
fn default() -> Self {
Self([0; 12])
}
}
impl core::fmt::Debug for Vec3 {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("Vec3")
.field("x", &self.x())
.field("y", &self.y())
.field("z", &self.z())
.finish()
}
}
impl flatbuffers::SimpleToVerifyInSlice for Vec3 {}
impl<'a> flatbuffers::Follow<'a> for Vec3 {
type Inner = &'a Vec3;
#[inline]
unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
<&'a Vec3>::follow(buf, loc)
}
}
impl<'a> flatbuffers::Follow<'a> for &'a Vec3 {
type Inner = &'a Vec3;
#[inline]
unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
flatbuffers::follow_cast_ref::<Vec3>(buf, loc)
}
}
impl<'b> flatbuffers::Push for Vec3 {
type Output = Vec3;
#[inline]
unsafe fn push(&self, dst: &mut [u8], _written_len: usize) {
let src = ::core::slice::from_raw_parts(self as *const Vec3 as *const u8, Self::size());
dst.copy_from_slice(src);
}
}
impl<'a> flatbuffers::Verifiable for Vec3 {
#[inline]
fn run_verifier(
v: &mut flatbuffers::Verifier, pos: usize
) -> Result<(), flatbuffers::InvalidFlatbuffer> {
use self::flatbuffers::Verifiable;
v.in_buffer::<Self>(pos)
}
}
impl<'a> Vec3 {
#[allow(clippy::too_many_arguments)]
pub fn new(
x: f32,
y: f32,
z: f32,
) -> Self {
let mut s = Self([0; 12]);
s.set_x(x);
s.set_y(y);
s.set_z(z);
s
}
pub const fn get_fully_qualified_name() -> &'static str {
"MyGame.Sample.Vec3"
}
pub fn x(&self) -> f32 {
let mut mem = core::mem::MaybeUninit::<<f32 as EndianScalar>::Scalar>::uninit();
// Safety:
// Created from a valid Table for this object
// Which contains a valid value in this slot
EndianScalar::from_little_endian(unsafe {
core::ptr::copy_nonoverlapping(
self.0[0..].as_ptr(),
mem.as_mut_ptr() as *mut u8,
core::mem::size_of::<<f32 as EndianScalar>::Scalar>(),
);
mem.assume_init()
})
}
pub fn set_x(&mut self, x: f32) {
let x_le = x.to_little_endian();
// Safety:
// Created from a valid Table for this object
// Which contains a valid value in this slot
unsafe {
core::ptr::copy_nonoverlapping(
&x_le as *const _ as *const u8,
self.0[0..].as_mut_ptr(),
core::mem::size_of::<<f32 as EndianScalar>::Scalar>(),
);
}
}
pub fn y(&self) -> f32 {
let mut mem = core::mem::MaybeUninit::<<f32 as EndianScalar>::Scalar>::uninit();
// Safety:
// Created from a valid Table for this object
// Which contains a valid value in this slot
EndianScalar::from_little_endian(unsafe {
core::ptr::copy_nonoverlapping(
self.0[4..].as_ptr(),
mem.as_mut_ptr() as *mut u8,
core::mem::size_of::<<f32 as EndianScalar>::Scalar>(),
);
mem.assume_init()
})
}
pub fn set_y(&mut self, x: f32) {
let x_le = x.to_little_endian();
// Safety:
// Created from a valid Table for this object
// Which contains a valid value in this slot
unsafe {
core::ptr::copy_nonoverlapping(
&x_le as *const _ as *const u8,
self.0[4..].as_mut_ptr(),
core::mem::size_of::<<f32 as EndianScalar>::Scalar>(),
);
}
}
pub fn z(&self) -> f32 {
let mut mem = core::mem::MaybeUninit::<<f32 as EndianScalar>::Scalar>::uninit();
// Safety:
// Created from a valid Table for this object
// Which contains a valid value in this slot
EndianScalar::from_little_endian(unsafe {
core::ptr::copy_nonoverlapping(
self.0[8..].as_ptr(),
mem.as_mut_ptr() as *mut u8,
core::mem::size_of::<<f32 as EndianScalar>::Scalar>(),
);
mem.assume_init()
})
}
pub fn set_z(&mut self, x: f32) {
let x_le = x.to_little_endian();
// Safety:
// Created from a valid Table for this object
// Which contains a valid value in this slot
unsafe {
core::ptr::copy_nonoverlapping(
&x_le as *const _ as *const u8,
self.0[8..].as_mut_ptr(),
core::mem::size_of::<<f32 as EndianScalar>::Scalar>(),
);
}
}
pub fn unpack(&self) -> Vec3T {
Vec3T {
x: self.x(),
y: self.y(),
z: self.z(),
}
}
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Vec3T {
pub x: f32,
pub y: f32,
pub z: f32,
}
impl Vec3T {
pub fn pack(&self) -> Vec3 {
Vec3::new(
self.x,
self.y,
self.z,
)
}
}
@@ -0,0 +1,168 @@
// automatically generated by the FlatBuffers compiler, do not modify
// @generated
extern crate alloc;
extern crate flatbuffers;
use alloc::boxed::Box;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::mem;
use core::cmp::Ordering;
use self::flatbuffers::{EndianScalar, Follow};
use super::*;
pub enum WeaponOffset {}
#[derive(Copy, Clone, PartialEq)]
pub struct Weapon<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for Weapon<'a> {
type Inner = Weapon<'a>;
#[inline]
unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self { _tab: flatbuffers::Table::new(buf, loc) }
}
}
impl<'a> Weapon<'a> {
pub const VT_NAME: flatbuffers::VOffsetT = 4;
pub const VT_DAMAGE: flatbuffers::VOffsetT = 6;
pub const fn get_fully_qualified_name() -> &'static str {
"MyGame.Sample.Weapon"
}
#[inline]
pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
Weapon { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>,
args: &'args WeaponArgs<'args>
) -> flatbuffers::WIPOffset<Weapon<'bldr>> {
let mut builder = WeaponBuilder::new(_fbb);
if let Some(x) = args.name { builder.add_name(x); }
builder.add_damage(args.damage);
builder.finish()
}
pub fn unpack(&self) -> WeaponT {
let name = self.name().map(|x| {
x.to_string()
});
let damage = self.damage();
WeaponT {
name,
damage,
}
}
#[inline]
pub fn name(&self) -> Option<&'a str> {
// Safety:
// Created from valid Table for this object
// which contains a valid value in this slot
unsafe { self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(Weapon::VT_NAME, None)}
}
#[inline]
pub fn damage(&self) -> i16 {
// Safety:
// Created from valid Table for this object
// which contains a valid value in this slot
unsafe { self._tab.get::<i16>(Weapon::VT_DAMAGE, Some(0)).unwrap()}
}
}
impl flatbuffers::Verifiable for Weapon<'_> {
#[inline]
fn run_verifier(
v: &mut flatbuffers::Verifier, pos: usize
) -> Result<(), flatbuffers::InvalidFlatbuffer> {
use self::flatbuffers::Verifiable;
v.visit_table(pos)?
.visit_field::<flatbuffers::ForwardsUOffset<&str>>("name", Self::VT_NAME, false)?
.visit_field::<i16>("damage", Self::VT_DAMAGE, false)?
.finish();
Ok(())
}
}
pub struct WeaponArgs<'a> {
pub name: Option<flatbuffers::WIPOffset<&'a str>>,
pub damage: i16,
}
impl<'a> Default for WeaponArgs<'a> {
#[inline]
fn default() -> Self {
WeaponArgs {
name: None,
damage: 0,
}
}
}
pub struct WeaponBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> WeaponBuilder<'a, 'b, A> {
#[inline]
pub fn add_name(&mut self, name: flatbuffers::WIPOffset<&'b str>) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Weapon::VT_NAME, name);
}
#[inline]
pub fn add_damage(&mut self, damage: i16) {
self.fbb_.push_slot::<i16>(Weapon::VT_DAMAGE, damage, 0);
}
#[inline]
pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> WeaponBuilder<'a, 'b, A> {
let start = _fbb.start_table();
WeaponBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<Weapon<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
impl core::fmt::Debug for Weapon<'_> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let mut ds = f.debug_struct("Weapon");
ds.field("name", &self.name());
ds.field("damage", &self.damage());
ds.finish()
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub struct WeaponT {
pub name: Option<String>,
pub damage: i16,
}
impl Default for WeaponT {
fn default() -> Self {
Self {
name: None,
damage: 0,
}
}
}
impl WeaponT {
pub fn pack<'b, A: flatbuffers::Allocator + 'b>(
&self,
_fbb: &mut flatbuffers::FlatBufferBuilder<'b, A>
) -> flatbuffers::WIPOffset<Weapon<'b>> {
let name = self.name.as_ref().map(|x|{
_fbb.create_string(x)
});
let damage = self.damage;
Weapon::create(_fbb, &WeaponArgs{
name,
damage,
})
}
}
+78
View File
@@ -0,0 +1,78 @@
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
#include "monster_generated.h" // Already includes "flatbuffers/flatbuffers.h".
using namespace MyGame::Sample;
// This is an example of parsing text straight into a buffer and then
// generating flatbuffer (JSON) text from the buffer.
int main(int /*argc*/, const char * /*argv*/[]) {
// load FlatBuffer schema (.fbs) and JSON from disk
std::string schema_file;
std::string json_file;
std::string bfbs_file;
bool ok =
flatbuffers::LoadFile("tests/monster_test.fbs", false, &schema_file) &&
flatbuffers::LoadFile("tests/monsterdata_test.golden", false,
&json_file) &&
flatbuffers::LoadFile("tests/monster_test.bfbs", true, &bfbs_file);
if (!ok) {
printf("couldn't load files!\n");
return 1;
}
const char *include_directories[] = { "samples", "tests",
"tests/include_test", nullptr };
// parse fbs schema
flatbuffers::Parser parser1;
ok = parser1.Parse(schema_file.c_str(), include_directories);
assert(ok);
// inizialize parser by deserializing bfbs schema
flatbuffers::Parser parser2;
ok = parser2.Deserialize(reinterpret_cast<const uint8_t *>(bfbs_file.c_str()),
bfbs_file.length());
assert(ok);
// parse json in parser from fbs and bfbs
ok = parser1.Parse(json_file.c_str(), include_directories);
assert(ok);
ok = parser2.Parse(json_file.c_str(), include_directories);
assert(ok);
// to ensure it is correct, we now generate text back from the binary,
// and compare the two:
std::string jsongen1;
if (GenText(parser1, parser1.builder_.GetBufferPointer(), &jsongen1)) {
printf("Couldn't serialize parsed data to JSON!\n");
return 1;
}
std::string jsongen2;
if (GenText(parser2, parser2.builder_.GetBufferPointer(), &jsongen2)) {
printf("Couldn't serialize parsed data to JSON!\n");
return 1;
}
if (jsongen1 != jsongen2) {
printf("%s----------------\n%s", jsongen1.c_str(), jsongen2.c_str());
}
printf("The FlatBuffer has been parsed from JSON successfully.\n");
}
+104
View File
@@ -0,0 +1,104 @@
/*
* Copyright 2015 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "monster_generated.h" // Already includes "flatbuffers/flatbuffers.h".
using namespace MyGame::Sample;
// Example how to use FlatBuffers to create and read binary buffers.
int main(int /*argc*/, const char * /*argv*/[]) {
// Build up a serialized buffer algorithmically:
flatbuffers::FlatBufferBuilder builder;
// First, lets serialize some weapons for the Monster: A 'sword' and an 'axe'.
auto weapon_one_name = builder.CreateString("Sword");
short weapon_one_damage = 3;
auto weapon_two_name = builder.CreateString("Axe");
short weapon_two_damage = 5;
// Use the `CreateWeapon` shortcut to create Weapons with all fields set.
auto sword = CreateWeapon(builder, weapon_one_name, weapon_one_damage);
auto axe = CreateWeapon(builder, weapon_two_name, weapon_two_damage);
// Create a FlatBuffer's `vector` from the `std::vector`.
std::vector<flatbuffers::Offset<Weapon>> weapons_vector;
weapons_vector.push_back(sword);
weapons_vector.push_back(axe);
auto weapons = builder.CreateVector(weapons_vector);
// Second, serialize the rest of the objects needed by the Monster.
auto position = Vec3(1.0f, 2.0f, 3.0f);
auto name = builder.CreateString("MyMonster");
unsigned char inv_data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
auto inventory = builder.CreateVector(inv_data, 10);
// Shortcut for creating monster with all fields set:
auto orc = CreateMonster(builder, &position, 150, 80, name, inventory,
Color_Red, weapons, Equipment_Weapon, axe.Union());
builder.Finish(orc); // Serialize the root of the object.
// We now have a FlatBuffer we can store on disk or send over a network.
// ** file/network code goes here :) **
// access builder.GetBufferPointer() for builder.GetSize() bytes
// Instead, we're going to access it right away (as if we just received it).
// Get access to the root:
auto monster = GetMonster(builder.GetBufferPointer());
// Get and test some scalar types from the FlatBuffer.
assert(monster->hp() == 80);
assert(monster->mana() == 150); // default
assert(monster->name()->str() == "MyMonster");
// Get and test a field of the FlatBuffer's `struct`.
auto pos = monster->pos();
assert(pos);
assert(pos->z() == 3.0f);
(void)pos;
// Get a test an element from the `inventory` FlatBuffer's `vector`.
auto inv = monster->inventory();
assert(inv);
assert(inv->Get(9) == 9);
(void)inv;
// Get and test the `weapons` FlatBuffers's `vector`.
std::string expected_weapon_names[] = { "Sword", "Axe" };
short expected_weapon_damages[] = { 3, 5 };
auto weps = monster->weapons();
for (unsigned int i = 0; i < weps->size(); i++) {
assert(weps->Get(i)->name()->str() == expected_weapon_names[i]);
assert(weps->Get(i)->damage() == expected_weapon_damages[i]);
}
(void)expected_weapon_names;
(void)expected_weapon_damages;
// Get and test the `Equipment` union (`equipped` field).
assert(monster->equipped_type() == Equipment_Weapon);
auto equipped = static_cast<const Weapon *>(monster->equipped());
assert(equipped->name()->str() == "Axe");
assert(equipped->damage() == 5);
(void)equipped;
printf("The FlatBuffer was successfully created and verified!\n");
}
+165
View File
@@ -0,0 +1,165 @@
/*
* Copyright 2015 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// To run, use the `go_sample.sh` script.
package main
import (
sample "github.com/google/flatbuffers/samples/MyGame/Sample"
"fmt"
flatbuffers "github.com/google/flatbuffers/go"
"strconv"
)
// Example how to use Flatbuffers to create and read binary buffers.
func main() {
builder := flatbuffers.NewBuilder(0)
// Create some weapons for our Monster ("Sword" and "Axe").
weaponOne := builder.CreateString("Sword")
weaponTwo := builder.CreateString("Axe")
sample.WeaponStart(builder)
sample.WeaponAddName(builder, weaponOne)
sample.WeaponAddDamage(builder, 3)
sword := sample.WeaponEnd(builder)
sample.WeaponStart(builder)
sample.WeaponAddName(builder, weaponTwo)
sample.WeaponAddDamage(builder, 5)
axe := sample.WeaponEnd(builder)
// Serialize the FlatBuffer data.
name := builder.CreateString("Orc")
sample.MonsterStartInventoryVector(builder, 10)
// Note: Since we prepend the bytes, this loop iterates in reverse.
for i := 9; i >= 0; i-- {
builder.PrependByte(byte(i))
}
inv := builder.EndVector(10)
sample.MonsterStartWeaponsVector(builder, 2)
// Note: Since we prepend the weapons, prepend in reverse order.
builder.PrependUOffsetT(axe)
builder.PrependUOffsetT(sword)
weapons := builder.EndVector(2)
pos := sample.CreateVec3(builder, 1.0, 2.0, 3.0)
sample.MonsterStart(builder)
sample.MonsterAddPos(builder, pos)
sample.MonsterAddHp(builder, 300)
sample.MonsterAddName(builder, name)
sample.MonsterAddInventory(builder, inv)
sample.MonsterAddColor(builder, sample.ColorRed)
sample.MonsterAddWeapons(builder, weapons)
sample.MonsterAddEquippedType(builder, sample.EquipmentWeapon)
sample.MonsterAddEquipped(builder, axe)
orc := sample.MonsterEnd(builder)
builder.Finish(orc)
// We now have a FlatBuffer that we could store on disk or send over a network.
// ...Saving to file or sending over a network code goes here...
// Instead, we are going to access this buffer right away (as if we just received it).
buf := builder.FinishedBytes()
// Note: We use `0` for the offset here, since we got the data using the
// `builder.FinishedBytes()` method. This simulates the data you would store/receive in your
// FlatBuffer. If you wanted to read from the `builder.Bytes` directly, you would need to
// pass in the offset of `builder.Head()`, as the builder actually constructs the buffer
// backwards.
monster := sample.GetRootAsMonster(buf, 0)
// Note: We did not set the `mana` field explicitly, so we get the
// default value.
assert(monster.Mana() == 150, "`monster.Mana()`", strconv.Itoa(int(monster.Mana())), "150")
assert(monster.Hp() == 300, "`monster.Hp()`", strconv.Itoa(int(monster.Hp())), "300")
assert(string(monster.Name()) == "Orc", "`string(monster.Name())`", string(monster.Name()),
"\"Orc\"")
assert(monster.Color() == sample.ColorRed, "`monster.Color()`",
strconv.Itoa(int(monster.Color())), strconv.Itoa(int(sample.ColorRed)))
// Note: Whenever you access a new object, like in `Pos()`, a new temporary accessor object
// gets created. If your code is very performance sensitive, you can pass in a pointer to an
// existing `Vec3` instead of `nil`. This allows you to reuse it across many calls to reduce
// the amount of object allocation/garbage collection.
assert(monster.Pos(nil).X() == 1.0, "`monster.Pos(nil).X()`",
strconv.FormatFloat(float64(monster.Pos(nil).X()), 'f', 1, 32), "1.0")
assert(monster.Pos(nil).Y() == 2.0, "`monster.Pos(nil).Y()`",
strconv.FormatFloat(float64(monster.Pos(nil).Y()), 'f', 1, 32), "2.0")
assert(monster.Pos(nil).Z() == 3.0, "`monster.Pos(nil).Z()`",
strconv.FormatFloat(float64(monster.Pos(nil).Z()), 'f', 1, 32), "3.0")
// For vectors, like `Inventory`, they have a method suffixed with 'Length' that can be used
// to query the length of the vector. You can index the vector by passing an index value
// into the accessor.
for i := 0; i < monster.InventoryLength(); i++ {
assert(monster.Inventory(i) == byte(i), "`monster.Inventory(i)`",
strconv.Itoa(int(monster.Inventory(i))), strconv.Itoa(int(byte(i))))
}
expectedWeaponNames := []string{"Sword", "Axe"}
expectedWeaponDamages := []int{3, 5}
weapon := new(sample.Weapon) // We need a `sample.Weapon` to pass into `monster.Weapons()`
// to capture the output of that function.
for i := 0; i < monster.WeaponsLength(); i++ {
if monster.Weapons(weapon, i) {
assert(string(weapon.Name()) == expectedWeaponNames[i], "`weapon.Name()`",
string(weapon.Name()), expectedWeaponNames[i])
assert(int(weapon.Damage()) == expectedWeaponDamages[i],
"`weapon.Damage()`", strconv.Itoa(int(weapon.Damage())),
strconv.Itoa(expectedWeaponDamages[i]))
}
}
// For FlatBuffer `union`s, you can get the type of the union, as well as the union
// data itself.
assert(monster.EquippedType() == sample.EquipmentWeapon, "`monster.EquippedType()`",
strconv.Itoa(int(monster.EquippedType())), strconv.Itoa(int(sample.EquipmentWeapon)))
unionTable := new(flatbuffers.Table)
if monster.Equipped(unionTable) {
// An example of how you can appropriately convert the table depending on the
// FlatBuffer `union` type. You could add `else if` and `else` clauses to handle
// other FlatBuffer `union` types for this field. (Similarly, this could be
// done in a switch statement.)
if monster.EquippedType() == sample.EquipmentWeapon {
unionWeapon := new(sample.Weapon)
unionWeapon.Init(unionTable.Bytes, unionTable.Pos)
assert(string(unionWeapon.Name()) == "Axe", "`unionWeapon.Name()`",
string(unionWeapon.Name()), "Axe")
assert(int(unionWeapon.Damage()) == 5, "`unionWeapon.Damage()`",
strconv.Itoa(int(unionWeapon.Damage())), strconv.Itoa(5))
}
}
fmt.Printf("The FlatBuffer was successfully created and verified!\n")
}
// A helper function to print out if an assertion failed.
func assert(assertPassed bool, codeExecuted string, actualValue string, expectedValue string) {
if assertPassed == false {
panic("Assert failed! " + codeExecuted + " (" + actualValue +
") was not equal to " + expectedValue + ".")
}
}
+100
View File
@@ -0,0 +1,100 @@
// Copyright 2018 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import from "../lobster/"
import monster_generated
// Example of how to use FlatBuffers to create and read binary buffers.
// Create a builder.
let b = flatbuffers_builder {}
// Create some weapons for our monster.
let weapon_names = [ "Sword", "Axe" ]
let weapon_damages = [ 3, 5 ]
let weapon_offsets = map(weapon_names) name, i:
let ns = b.CreateString(name)
MyGame_Sample_WeaponBuilder { b }
.start()
.add_name(ns)
.add_damage(weapon_damages[i])
.end()
let weapons = b.MyGame_Sample_MonsterCreateWeaponsVector(weapon_offsets)
// Name of the monster.
let name = b.CreateString("Orc")
// Inventory.
let inv = b.MyGame_Sample_MonsterCreateInventoryVector(map(10): _)
// Now pack it all together in our root monster object.
let orc = MyGame_Sample_MonsterBuilder { b }
.start()
.add_pos(b.MyGame_Sample_CreateVec3(1.0, 2.0, 3.0))
.add_hp(300)
.add_name(name)
.add_inventory(inv)
.add_color(MyGame_Sample_Color_Red)
.add_weapons(weapons)
.add_equipped_type(MyGame_Sample_Equipment_Weapon)
.add_equipped(weapon_offsets[1])
.end()
// Finish the buffer!
b.Finish(orc, "MONS")
// We now have a FlatBuffer that we could store on disk or send over a network.
let buf = b.SizedCopy()
// ...Saving to file or sending over a network code goes here...
// Instead, we are going to access this buffer right away (as if we just
// received it).
// Get the root object accessor.
let monster = MyGame_Sample_GetRootAsMonster(buf)
// Note: We did not set the `mana` field explicitly, so we get a default value.
assert monster.mana == 150
assert monster.hp == 300
assert monster.name == "Orc"
assert monster.color == MyGame_Sample_Color_Red
let pos = monster.pos
assert pos
assert pos.x == 1.0
assert pos.y == 2.0
assert pos.z == 3.0
// Get and test the `inventory` FlatBuffer vector.
for(monster.inventory_length) e, i:
assert monster.inventory(i) == e
// Get and test the `weapons` FlatBuffer vector of tables.
for(monster.weapons_length) i:
assert monster.weapons(i).name == weapon_names[i]
assert monster.weapons(i).damage == weapon_damages[i]
// Get and test the `equipped` FlatBuffer union.
assert monster.equipped_type() == MyGame_Sample_Equipment_Weapon
// Now that we know the union value is a weapon, we can safely call as_Weapon:
let union_weapon = monster.equipped_as_Weapon
assert union_weapon.name == "Axe"
assert union_weapon.damage == 5
print "The FlatBuffer was successfully created and verified!"
+107
View File
@@ -0,0 +1,107 @@
-- need to update the Lua path to point to the local flatbuffers implementation
package.path = string.format("../lua/?.lua;%s",package.path)
package.path = string.format("./lua/?.lua;%s",package.path)
-- require the library
local flatbuffers = require("flatbuffers")
local binaryArray = flatbuffers.binaryArray-- for hex dump utility
-- require the files generated from the schema
local weapon = require("MyGame.Sample.Weapon")
local monster = require("MyGame.Sample.Monster")
local vec3 = require("MyGame.Sample.Vec3")
local color = require("MyGame.Sample.Color")
local equipment = require("MyGame.Sample.Equipment")
-- get access to the builder, providing an array of size 1024
local builder = flatbuffers.Builder(1024)
local weaponOne = builder:CreateString("Sword")
local weaponTwo = builder:CreateString("Axe")
-- Create the first 'Weapon'
weapon.Start(builder)
weapon.AddName(builder, weaponOne)
weapon.AddDamage(builder, 3)
local sword = weapon.End(builder)
-- Create the second 'Weapon'
weapon.Start(builder)
weapon.AddName(builder, weaponTwo)
weapon.AddDamage(builder, 5)
local axe = weapon.End(builder)
-- Serialize a name for our mosnter, called 'orc'
local name = builder:CreateString("Orc")
-- Create a `vector` representing the inventory of the Orc. Each number
-- could correspond to an item that can be claimed after he is slain.
-- Note: Since we prepend the bytes, this loop iterates in reverse.
monster.StartInventoryVector(builder, 10)
for i=10,1,-1 do
builder:PrependByte(i)
end
local inv = builder:EndVector(10)
-- Create a FlatBuffer vector and prepend the weapons.
-- Note: Since we prepend the data, prepend them in reverse order.
monster.StartWeaponsVector(builder, 2)
builder:PrependUOffsetTRelative(axe)
builder:PrependUOffsetTRelative(sword)
local weapons = builder:EndVector(2)
-- Create our monster by using Start() andEnd()
monster.Start(builder)
monster.AddPos(builder, vec3.CreateVec3(builder, 1.0, 2.0, 3.0))
monster.AddHp(builder, 300)
monster.AddName(builder, name)
monster.AddInventory(builder, inv)
monster.AddColor(builder, color.Red)
monster.AddWeapons(builder, weapons)
monster.AddEquippedType(builder, equipment.Weapon)
monster.AddEquipped(builder, axe)
local orc = monster.End(builder)
-- Call 'Finish()' to instruct the builder that this monster is complete.
builder:Finish(orc)
-- Get the flatbuffer as a string containing the binary data
local bufAsString = builder:Output()
-- Convert the string representation into binary array Lua structure
local buf = flatbuffers.binaryArray.New(bufAsString)
-- Get an accessor to the root object insert the buffer
local mon = monster.GetRootAsMonster(buf, 0)
assert(mon:Mana() == 150)
assert(mon:Hp() == 300)
assert(mon:Name() == "Orc")
assert(mon:Color() == color.Red)
assert(mon:Pos():X() == 1.0)
assert(mon:Pos():Y() == 2.0)
assert(mon:Pos():Z() == 3.0)
for i=1,mon:InventoryLength() do
assert(mon:Inventory(i) == i)
end
local expected = {
{w = 'Sword', d = 3},
{w = 'Axe', d = 5}
}
for i=1,mon:WeaponsLength() do
assert(mon:Weapons(i):Name() == expected[i].w)
assert(mon:Weapons(i):Damage() == expected[i].d)
end
assert(mon:EquippedType() == equipment.Weapon)
local unionWeapon = weapon.New()
unionWeapon:Init(mon:Equipped().bytes,mon:Equipped().pos)
assert(unionWeapon:Name() == "Axe")
assert(unionWeapon:Damage() == 5)
print("The Lua FlatBuffer example was successfully created and verified!")
+137
View File
@@ -0,0 +1,137 @@
#!/usr/bin/python
# Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# To run this file, use `python_sample.sh`.
# Append paths to the `flatbuffers` and `MyGame` modules. This is necessary
# to facilitate executing this script in the `samples` folder, and to root
# folder (where it gets placed when using `cmake`).
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '../python'))
import flatbuffers
import MyGame.Sample.Color
import MyGame.Sample.Equipment
import MyGame.Sample.Monster
import MyGame.Sample.Vec3
import MyGame.Sample.Weapon
# Example of how to use FlatBuffers to create and read binary buffers.
def main():
builder = flatbuffers.Builder(0)
# Create some weapons for our Monster ('Sword' and 'Axe').
weapon_one = builder.CreateString('Sword')
weapon_two = builder.CreateString('Axe')
MyGame.Sample.Weapon.WeaponStart(builder)
MyGame.Sample.Weapon.WeaponAddName(builder, weapon_one)
MyGame.Sample.Weapon.WeaponAddDamage(builder, 3)
sword = MyGame.Sample.Weapon.WeaponEnd(builder)
MyGame.Sample.Weapon.WeaponStart(builder)
MyGame.Sample.Weapon.WeaponAddName(builder, weapon_two)
MyGame.Sample.Weapon.WeaponAddDamage(builder, 5)
axe = MyGame.Sample.Weapon.WeaponEnd(builder)
# Serialize the FlatBuffer data.
name = builder.CreateString('Orc')
MyGame.Sample.Monster.MonsterStartInventoryVector(builder, 10)
# Note: Since we prepend the bytes, this loop iterates in reverse order.
for i in reversed(range(0, 10)):
builder.PrependByte(i)
inv = builder.EndVector()
MyGame.Sample.Monster.MonsterStartWeaponsVector(builder, 2)
# Note: Since we prepend the data, prepend the weapons in reverse order.
builder.PrependUOffsetTRelative(axe)
builder.PrependUOffsetTRelative(sword)
weapons = builder.EndVector()
pos = MyGame.Sample.Vec3.CreateVec3(builder, 1.0, 2.0, 3.0)
MyGame.Sample.Monster.MonsterStart(builder)
MyGame.Sample.Monster.MonsterAddPos(builder, pos)
MyGame.Sample.Monster.MonsterAddHp(builder, 300)
MyGame.Sample.Monster.MonsterAddName(builder, name)
MyGame.Sample.Monster.MonsterAddInventory(builder, inv)
MyGame.Sample.Monster.MonsterAddColor(builder,
MyGame.Sample.Color.Color().Red)
MyGame.Sample.Monster.MonsterAddWeapons(builder, weapons)
MyGame.Sample.Monster.MonsterAddEquippedType(
builder, MyGame.Sample.Equipment.Equipment().Weapon)
MyGame.Sample.Monster.MonsterAddEquipped(builder, axe)
orc = MyGame.Sample.Monster.MonsterEnd(builder)
builder.Finish(orc)
# We now have a FlatBuffer that we could store on disk or send over a network.
# ...Saving to file or sending over a network code goes here...
# Instead, we are going to access this buffer right away (as if we just
# received it).
buf = builder.Output()
# Note: We use `0` for the offset here, since we got the data using the
# `builder.Output()` method. This simulates the data you would store/receive
# in your FlatBuffer. If you wanted to read from the `builder.Bytes` directly,
# you would need to pass in the offset of `builder.Head()`, as the builder
# actually constructs the buffer backwards.
monster = MyGame.Sample.Monster.Monster.GetRootAsMonster(buf, 0)
# Note: We did not set the `Mana` field explicitly, so we get a default value.
assert monster.Mana() == 150
assert monster.Hp() == 300
assert monster.Name() == b'Orc'
assert monster.Color() == MyGame.Sample.Color.Color().Red
assert monster.Pos().X() == 1.0
assert monster.Pos().Y() == 2.0
assert monster.Pos().Z() == 3.0
# Get and test the `inventory` FlatBuffer `vector`.
for i in range(monster.InventoryLength()):
assert monster.Inventory(i) == i
# Get and test the `weapons` FlatBuffer `vector` of `table`s.
expected_weapon_names = [b'Sword', b'Axe']
expected_weapon_damages = [3, 5]
for i in range(monster.WeaponsLength()):
assert monster.Weapons(i).Name() == expected_weapon_names[i]
assert monster.Weapons(i).Damage() == expected_weapon_damages[i]
# Get and test the `equipped` FlatBuffer `union`.
assert monster.EquippedType() == MyGame.Sample.Equipment.Equipment().Weapon
# An example of how you can appropriately convert the table depending on the
# FlatBuffer `union` type. You could add `elif` and `else` clauses to handle
# the other FlatBuffer `union` types for this field.
if monster.EquippedType() == MyGame.Sample.Equipment.Equipment().Weapon:
# `monster.Equipped()` returns a `flatbuffers.Table`, which can be used
# to initialize a `MyGame.Sample.Weapon.Weapon()`, in this case.
union_weapon = MyGame.Sample.Weapon.Weapon()
union_weapon.Init(monster.Equipped().Bytes, monster.Equipped().Pos)
assert union_weapon.Name() == b"Axe"
assert union_weapon.Damage() == 5
print('The FlatBuffer was successfully created and verified!')
if __name__ == '__main__':
main()
+159
View File
@@ -0,0 +1,159 @@
/*
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// import the flatbuffers runtime library
extern crate flatbuffers;
// import the generated code
#[allow(dead_code, unused_imports)]
#[allow(clippy::all)]
mod rust_generated;
pub use rust_generated::my_game::sample::{Color, Equipment,
Monster, MonsterArgs,
Vec3,
Weapon, WeaponArgs};
// Example how to use FlatBuffers to create and read binary buffers.
#[allow(clippy::float_cmp)]
fn main() {
// Build up a serialized buffer algorithmically.
// Initialize it with a capacity of 1024 bytes.
let mut builder = flatbuffers::FlatBufferBuilder::with_capacity(1024);
// Serialize some weapons for the Monster: A 'sword' and an 'axe'.
let weapon_one_name = builder.create_string("Sword");
let weapon_two_name = builder.create_string("Axe");
// Use the `Weapon::create` shortcut to create Weapons with named field
// arguments.
let sword = Weapon::create(&mut builder, &WeaponArgs{
name: Some(weapon_one_name),
damage: 3,
});
let axe = Weapon::create(&mut builder, &WeaponArgs{
name: Some(weapon_two_name),
damage: 5,
});
// Name of the Monster.
let name = builder.create_string("Orc");
// Inventory.
let inventory = builder.create_vector(&[0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
// Create a FlatBuffer `vector` that contains offsets to the sword and axe
// we created above.
let weapons = builder.create_vector(&[sword, axe]);
// Create the path vector of Vec3 objects:
//let x = Vec3::new(1.0, 2.0, 3.0);
//let y = Vec3::new(4.0, 5.0, 6.0);
//let path = builder.create_vector(&[x, y]);
// Note that, for convenience, it is also valid to create a vector of
// references to structs, like this:
// let path = builder.create_vector(&[&x, &y]);
// Create the monster using the `Monster::create` helper function. This
// function accepts a `MonsterArgs` struct, which supplies all of the data
// needed to build a `Monster`. To supply empty/default fields, just use the
// Rust built-in `Default::default()` function, as demonstrated below.
let orc = Monster::create(&mut builder, &MonsterArgs{
pos: Some(&Vec3::new(1.0f32, 2.0f32, 3.0f32)),
mana: 150,
hp: 80,
name: Some(name),
inventory: Some(inventory),
color: Color::Red,
weapons: Some(weapons),
equipped_type: Equipment::Weapon,
equipped: Some(axe.as_union_value()),
//path: Some(path),
..Default::default()
});
// Serialize the root of the object, without providing a file identifier.
builder.finish(orc, None);
// We now have a FlatBuffer we can store on disk or send over a network.
// ** file/network code goes here :) **
// Instead, we're going to access it right away (as if we just received it).
// This must be called after `finish()`.
let buf = builder.finished_data(); // Of type `&[u8]`
// Get access to the root:
let monster = flatbuffers::root::<Monster>(buf).unwrap();
// Get and test some scalar types from the FlatBuffer.
let hp = monster.hp();
let mana = monster.mana();
let name = monster.name();
assert_eq!(hp, 80);
assert_eq!(mana, 150); // default
assert_eq!(name, Some("Orc"));
// Get and test a field of the FlatBuffer's `struct`.
assert!(monster.pos().is_some());
let pos = monster.pos().unwrap();
let x = pos.x();
let y = pos.y();
let z = pos.z();
assert_eq!(x, 1.0f32);
assert_eq!(y, 2.0f32);
assert_eq!(z, 3.0f32);
// Get an element from the `inventory` FlatBuffer's `vector`.
assert!(monster.inventory().is_some());
let inv = monster.inventory().unwrap();
let third_item = inv.get(2);
assert_eq!(third_item, 2);
// Get and test the `weapons` FlatBuffers's `vector`.
assert!(monster.weapons().is_some());
let weps = monster.weapons().unwrap();
//let weps_len = weps.len();
let wep2 = weps.get(1);
let second_weapon_name = wep2.name();
let second_weapon_damage = wep2.damage();
assert_eq!(second_weapon_name, Some("Axe"));
assert_eq!(second_weapon_damage, 5);
// Get and test the `Equipment` union (`equipped` field).
assert_eq!(monster.equipped_type(), Equipment::Weapon);
let equipped = monster.equipped_as_weapon().unwrap();
let weapon_name = equipped.name();
let weapon_damage = equipped.damage();
assert_eq!(weapon_name, Some("Axe"));
assert_eq!(weapon_damage, 5);
// Get and test the `path` FlatBuffers's `vector`.
//assert_eq!(monster.path().unwrap().len(), 2);
//assert_eq!(monster.path().unwrap()[0].x(), 1.0);
//assert_eq!(monster.path().unwrap()[1].x(), 4.0);
println!("The FlatBuffer was successfully created and accessed!");
dbg!(monster);
}
#[cfg(test)]
#[test]
fn test_main() {
main()
}
+83
View File
@@ -0,0 +1,83 @@
/*
* Copyright 2023 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import FlatBuffers
typealias Monster = MyGame_Sample_Monster
typealias Weapon = MyGame_Sample_Weapon
typealias Color = MyGame_Sample_Color
typealias Vec3 = MyGame_Sample_Vec3
func main() {
let expectedDMG: [Int16] = [3, 5]
let expectedNames = ["Sword", "Axe"]
var builder = FlatBufferBuilder(initialSize: 1024)
let weapon1Name = builder.create(string: expectedNames[0])
let weapon2Name = builder.create(string: expectedNames[1])
let weapon1Start = Weapon.startWeapon(&builder)
Weapon.add(name: weapon1Name, &builder)
Weapon.add(damage: expectedDMG[0], &builder)
let sword = Weapon.endWeapon(&builder, start: weapon1Start)
let weapon2Start = Weapon.startWeapon(&builder)
Weapon.add(name: weapon2Name, &builder)
Weapon.add(damage: expectedDMG[1], &builder)
let axe = Weapon.endWeapon(&builder, start: weapon2Start)
let name = builder.create(string: "Orc")
let inventory: [Byte] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
let inventoryOffset = builder.createVector(inventory)
let weaponsOffset = builder.createVector(ofOffsets: [sword, axe])
let orc = Monster.createMonster(
&builder,
pos: MyGame_Sample_Vec3(x: 1, y: 2, z: 3),
hp: 300,
nameOffset: name,
inventoryVectorOffset: inventoryOffset,
color: .red,
weaponsVectorOffset: weaponsOffset,
equippedType: .weapon,
equippedOffset: axe)
builder.finish(offset: orc)
var buf = ByteBuffer(bytes: builder.sizedByteArray)
let monster: Monster = try! getCheckedRoot(byteBuffer: &buffer)
assert(monster.mana == 150)
assert(monster.hp == 300)
assert(monster.name == "Orc")
assert(monster.color == MyGame.Sample.Color.red)
assert(monster.pos != nil)
assert(monster.mutablePos != nil)
for i in 0..<monster.inventoryCount {
assert(i == monster.inventory(at: i))
}
for i in 0..<monster.weaponsCount {
let weap = monster.weapons(at: i)
let index = Int(i)
assert(weap?.damage == expectedDMG[index])
assert(weap?.name == expectedNames[index])
}
assert(monster.equippedType == .weapon)
let equipped = monster.equipped(type: Weapon.self)
assert(equipped?.name == "Axe")
assert(equipped?.damage == 5)
print("Monster Object is Verified")
}
+166
View File
@@ -0,0 +1,166 @@
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate flexbuffers;
use flexbuffers::{BitWidth, Builder, Reader, ReaderError};
// In this Example we're creating a monster that corresponds to the following JSON:
// {
// "coins": [5, 10, 25, 25, 25, 100],
// "color": [255, 0, 0, 255],
// "enraged": true,
// "hp": 80,
// "mana": 200,
// "position": [0, 0, 0],
// "velocity": [1, 0, 0],
// "weapons": [
// "fist",
// {"damage": 15, "name": "great axe"},
// {"damage": 5, "name": "hammer"}]
// }
#[allow(clippy::float_cmp)]
fn main() {
// Create a new Flexbuffer builder.
let mut builder = Builder::default();
// The root of the builder can be a singleton, map or vector.
// Our monster will be represented with a map.
let mut monster = builder.start_map();
// Use `push` to add elements to a vector or map. Note that it up to the programmer to ensure
// duplicate keys are avoided and the key has no null bytes.
monster.push("hp", 80);
monster.push("mana", 200);
monster.push("enraged", true);
// Let's give our monster some weapons. Use `start_vector` to store a vector.
let mut weapons = monster.start_vector("weapons");
// The first weapon is a fist which has no damage so we'll store it as a string.
// Strings in Flexbuffers are utf8 encoded and are distinct from map Keys which are c strings.
weapons.push("fist");
// The monster also has an axe. We'll store it as a map to make it more interesting.
let mut axe = weapons.start_map();
axe.push("name", "great axe");
axe.push("damage", 15);
// We're done adding to the axe.
axe.end_map();
// The monster also has a hammer.
{
let mut hammer = weapons.start_map();
hammer.push("name", "hammer");
hammer.push("damage", 5);
// Instead of calling `hammer.end_map()`, we can just drop the `hammer` for the same effect.
// Vectors and maps are completed and serialized when their builders are dropped.
}
// We're done adding weapons.
weapons.end_vector();
// Give the monster some money. Flexbuffers has typed vectors which are smaller than
// heterogenous vectors. Elements of typed vectors can be pushed one at a time, as above, or
// they can be passed as a slice. This will be stored as a `FlexBufferType::VectorInt`.
monster.push("coins", &[5, 10, 25, 25, 25, 100]);
// Flexbuffer has special types for fixed-length-typed-vectors (if the length is 3 or 4 and the
// type is int, uint, or float). They're even more compact than typed vectors.
// The monster's position and Velocity will be stored as `FlexbufferType::VectorFloat3`.
monster.push("position", &[0.0; 3]);
monster.push("velocity", &[1.0, 0.0, 0.0]);
// Give the monster bright red skin. In rust, numbers are assumed integers until proven
// otherwise. We annotate u8 to tell flexbuffers to store it as a FlexbufferType::VectorUInt4.
monster.push("color", &[255, 0, 0, 255u8]);
// End the map at the root of the builder. This finishes the Flexbuffer.
monster.end_map();
// Now the buffer is free to be reused. Let's see the final buffer.
let data = builder.view();
println!("The monster was serialized in {:?} bytes.", data.len());
// Let's read and verify the data.
let root = Reader::get_root(data).unwrap();
println!("The monster: {}", root);
let read_monster = root.as_map();
// What attributes does this monster have?
let attrs: Vec<_> = read_monster.iter_keys().collect();
assert_eq!(
attrs,
vec!["coins", "color", "enraged", "hp", "mana", "position", "velocity", "weapons"]
);
// index into a vector or map with the `idx` method.
let read_hp = read_monster.idx("hp");
let read_mana = read_monster.idx("mana");
// If `idx` fails it will return a Null flexbuffer Reader
// Use `as_T` to cast the data to your desired type.
assert_eq!(read_hp.as_u8(), 80);
assert_eq!(read_hp.as_f32(), 80.0);
// If it fails it will return T::default().
assert_eq!(read_hp.as_str(), ""); // Its not a string.
assert_eq!(read_mana.as_i8(), 0); // 200 is not representable in i8.
assert!(read_mana.as_vector().is_empty()); // Its not a vector.
assert_eq!(read_monster.idx("foo").as_i32(), 0); // `foo` is not a monster attribute.
// To examine how your data is stored, check the flexbuffer type and bitwidth.
assert!(read_hp.flexbuffer_type().is_int());
assert!(read_mana.flexbuffer_type().is_int());
// Note that mana=200 is bigger than the maximum i8 so everything in the top layer of the
// monster map is stored in 16 bits.
assert_eq!(read_hp.bitwidth(), BitWidth::W16);
assert_eq!(read_monster.idx("mana").bitwidth(), BitWidth::W16);
// Use get_T functions if you want to ensure the flexbuffer type matches what you expect.
assert_eq!(read_hp.get_i64(), Ok(80));
assert!(read_hp.get_u64().is_err());
assert!(read_hp.get_vector().is_err());
// Analogously, the `index` method is the safe version of `idx`.
assert!(read_monster.index("hp").is_ok());
assert_eq!(
read_monster.index("foo").unwrap_err(),
ReaderError::KeyNotFound
);
// Maps can also be indexed by usize. They're stored by key so `coins` are the first element.
let monster_coins = read_monster.idx(0);
// Maps and Vectors can be iterated over.
assert!(monster_coins
.as_vector()
.iter()
.map(|r| r.as_u8())
.eq(vec![5, 10, 25, 25, 25, 100].into_iter()));
// Build the answer to life the universe and everything. Reusing a builder resets it. The
// reused internals won't need to reallocate leading to a potential 2x speedup.
builder.build_singleton(42);
// The monster is now no more.
assert_eq!(builder.view().len(), 3); // Bytes.
let the_answer = Reader::get_root(builder.view()).unwrap();
assert_eq!(the_answer.as_i32(), 42);
}
#[test]
fn test_main() {
main()
}
@@ -0,0 +1,81 @@
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate flexbuffers;
extern crate serde;
#[macro_use]
extern crate serde_derive;
use serde::{Deserialize, Serialize};
#[derive(Debug, PartialEq, Serialize, Deserialize)]
enum Weapon {
Fist,
Equipment { name: String, damage: i32 },
}
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Color(u8, u8, u8, u8);
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Monster {
hp: u32,
mana: i32,
enraged: bool,
weapons: Vec<Weapon>,
color: Color,
position: [f64; 3],
velocity: [f64; 3],
coins: Vec<u32>,
}
fn main() {
let monster = Monster {
hp: 80,
mana: 200,
enraged: true,
color: Color(255, 255, 255, 255),
position: [0.0; 3],
velocity: [1.0, 0.0, 0.0],
weapons: vec![
Weapon::Fist,
Weapon::Equipment {
name: "great axe".to_string(),
damage: 15,
},
Weapon::Equipment {
name: "hammer".to_string(),
damage: 5,
},
],
coins: vec![5, 10, 25, 25, 25, 100],
};
let mut s = flexbuffers::FlexbufferSerializer::new();
monster.serialize(&mut s).unwrap();
let r = flexbuffers::Reader::get_root(s.view()).unwrap();
// Serialization is similar to JSON. Field names are stored in the buffer but are reused
// between all maps and structs.
println!("Monster stored in {:?} bytes.", s.view().len());
println!("{}", r);
let monster2 = Monster::deserialize(r).unwrap();
assert_eq!(monster, monster2);
}
#[test]
fn test_main() {
main()
}
+58
View File
@@ -0,0 +1,58 @@
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
#include "monster_generated.h" // Already includes "flatbuffers/flatbuffers.h".
using namespace MyGame::Sample;
// This is an example of parsing text straight into a buffer and then
// generating flatbuffer (JSON) text from the buffer.
int main(int /*argc*/, const char * /*argv*/[]) {
// load FlatBuffer schema (.fbs) and JSON from disk
std::string schemafile;
std::string jsonfile;
bool ok = flatbuffers::LoadFile("samples/monster.fbs", false, &schemafile) &&
flatbuffers::LoadFile("samples/monsterdata.json", false, &jsonfile);
if (!ok) {
printf("couldn't load files!\n");
return 1;
}
// parse schema first, so we can use it to parse the data after
flatbuffers::Parser parser;
const char *include_directories[] = { "samples", nullptr };
ok = parser.Parse(schemafile.c_str(), include_directories) &&
parser.Parse(jsonfile.c_str(), include_directories);
assert(ok);
// here, parser.builder_ contains a binary buffer that is the parsed data.
// to ensure it is correct, we now generate text back from the binary,
// and compare the two:
std::string jsongen;
if (GenText(parser, parser.builder_.GetBufferPointer(), &jsongen)) {
printf("Couldn't serialize parsed data to JSON!\n");
return 1;
}
if (jsongen != jsonfile) {
printf("%s----------------\n%s", jsongen.c_str(), jsonfile.c_str());
}
printf("The FlatBuffer has been parsed from JSON successfully.\n");
}
+43
View File
@@ -0,0 +1,43 @@
// Copyright 2018 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import from "../lobster/"
import monster_generated
// Example how to interop with JSON.
// Test loading some JSON, converting it to a binary FlatBuffer and back again.
// First read the schema and JSON data.
let schema = read_file("monster.fbs", true)
let json = read_file("monsterdata.json", true)
assert schema and json
// Parse JSON to binary:
let fb, err1 = flatbuffers_json_to_binary(schema, json, [])
assert not err1
// Access one field in it, just to check:
let monster = MyGame_Sample_GetRootAsMonster(fb)
assert monster.name == "Orc"
// Convert binary back to JSON:
let json2, err2 = flatbuffers_binary_to_json(schema, fb, [])
assert not err2
// The generated JSON should be exactly equal to the original!
assert json == json2
// Print what we've been converting for good measure:
print json