add flatbuffers

commit 6da1cf79d90eb242e7da5318241d42279a3df3ba
Author: Max Burke <max@urbanlogiq.com>
Date:   Sun Jan 19 14:47:28 2020 -0800

    [rust] Add use declarations to Rust-generated bindings for imported FB definitions (#5645)

    * Bugfix for Rust generation of union fields named with language keywords
This commit is contained in:
carbon
2024-05-31 14:12:12 +08:00
parent 3e2ce5494f
commit 93b1517102
685 changed files with 147856 additions and 0 deletions

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 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);
}
}
}

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!");
}
}

View File

@ -0,0 +1,108 @@
/*
* 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
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)
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.toByte().toInt())
}
// 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!")
}
}
}

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();
?>

View File

@ -0,0 +1,45 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (c) 2015 Google, Inc.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
-->
<!-- BEGIN_INCLUDE(manifest) -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.samples.FlatBufferSample">
<uses-feature android:glEsVersion="0x00020000"></uses-feature>
<!-- This .apk has no Java code itself, so set hasCode to false. -->
<application android:label="@string/app_name"
android:hasCode="false"
android:allowBackup="false">
<!-- Our activity is the built-in NativeActivity framework class.
This will take care of integrating with our NDK code. -->
<activity android:name="android.app.NativeActivity"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="landscape">
<!-- Tell NativeActivity the name of or .so -->
<meta-data android:name="android.app.lib_name"
android:value="FlatBufferSample" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
<!-- END_INCLUDE(manifest) -->

View File

@ -0,0 +1,108 @@
// Copyright (c) 2017 Google, Inc.
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.0'
}
}
allprojects {
repositories {
jcenter()
}
}
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion '25.0.2'
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
res.srcDirs = ['res']
}
}
externalNativeBuild {
ndkBuild {
path "jni/Android.mk"
}
}
defaultConfig {
applicationId 'com.samples.FlatBufferSample'
// This is the platform API where NativeActivity was introduced.
minSdkVersion 9
targetSdkVersion 25
versionCode 1
versionName "1.0"
buildTypes {
release {
minifyEnabled false
}
}
externalNativeBuild {
ndkBuild {
targets "FlatBufferSample"
arguments "-j" + Runtime.getRuntime().availableProcessors()
abiFilters "armeabi-v7a", "arm64-v8a", "x86", "x86_64"
}
}
}
lintOptions {
abortOnError false
}
// Build with each STL variant.
productFlavors {
stlport {
applicationIdSuffix ".stlport"
versionNameSuffix "-stlport"
externalNativeBuild {
ndkBuild {
arguments "APP_STL=stlport_static"
}
}
}
gnustl {
applicationIdSuffix ".gnustl"
versionNameSuffix "-gnustl"
externalNativeBuild {
ndkBuild {
arguments "APP_STL=gnustl_static"
}
}
}
libcpp {
applicationIdSuffix ".libcpp"
versionNameSuffix "-libcpp"
externalNativeBuild {
ndkBuild {
arguments "APP_STL=c++_static"
}
}
}
}
}

Binary file not shown.

View File

@ -0,0 +1,6 @@
#Mon Jun 19 11:54:59 PDT 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.0-all.zip

172
flatbuffers/samples/android/gradlew vendored Executable file
View File

@ -0,0 +1,172 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

84
flatbuffers/samples/android/gradlew.bat vendored Normal file
View File

@ -0,0 +1,84 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -0,0 +1,56 @@
# Copyright (c) 2013 Google, Inc.
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any damages
# arising from the use of this software.
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
# 1. The origin of this software must not be misrepresented; you must not
# claim that you wrote the original software. If you use this software
# in a product, an acknowledgment in the product documentation would be
# appreciated but is not required.
# 2. Altered source versions must be plainly marked as such, and must not be
# misrepresented as being the original software.
# 3. This notice may not be removed or altered from any source distribution.
LOCAL_PATH := $(call my-dir)
FLATBUFFERS_ROOT_DIR := $(LOCAL_PATH)/../../..
# FlatBuffers test
include $(CLEAR_VARS)
# Include the FlatBuffer utility function to generate header files from schemas.
include $(FLATBUFFERS_ROOT_DIR)/android/jni/include.mk
LOCAL_MODULE := FlatBufferSample
# Set up some useful variables to identify schema and output directories and
# schema files.
ANDROID_SAMPLE_GENERATED_OUTPUT_DIR := $(LOCAL_PATH)/gen/include
ANDROID_SAMPLE_SCHEMA_DIR := $(LOCAL_PATH)/schemas
ANDROID_SAMPLE_SCHEMA_FILES := $(ANDROID_SAMPLE_SCHEMA_DIR)/animal.fbs
LOCAL_C_INCLUDES := $(ANDROID_SAMPLE_GENERATED_OUTPUT_DIR)
$(info $(LOCAL_C_INCLUDES))
LOCAL_SRC_FILES := main.cpp
LOCAL_CPPFLAGS := -std=c++11 -fexceptions -Wall -Wno-literal-suffix
LOCAL_LDLIBS := -llog -landroid -latomic
LOCAL_ARM_MODE := arm
LOCAL_STATIC_LIBRARIES := android_native_app_glue flatbuffers
ifeq (,$(ANDROID_SAMPLE_RUN_ONCE))
ANDROID_SAMPLE_RUN_ONCE := 1
$(call flatbuffers_header_build_rules,$(ANDROID_SAMPLE_SCHEMA_FILES),$(ANDROID_SAMPLE_SCHEMA_DIR),$(ANDROID_SAMPLE_GENERATED_OUTPUT_DIR),,$(LOCAL_SRC_FILES))
endif
include $(BUILD_SHARED_LIBRARY)
# Path to Flatbuffers root directory.
$(call import-add-path,$(FLATBUFFERS_ROOT_DIR)/..)
$(call import-module,flatbuffers/android/jni)
$(call import-module,android/native_app_glue)

View File

@ -0,0 +1,20 @@
# Copyright (c) 2014 Google, Inc.
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any damages
# arising from the use of this software.
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
# 1. The origin of this software must not be misrepresented; you must not
# claim that you wrote the original software. If you use this software
# in a product, an acknowledgment in the product documentation would be
# appreciated but is not required.
# 2. Altered source versions must be plainly marked as such, and must not be
# misrepresented as being the original software.
# 3. This notice may not be removed or altered from any source distribution.
APP_PLATFORM := android-9
APP_PROJECT_PATH := $(call my-dir)/..
APP_STL ?= stlport_static
APP_ABI := armeabi-v7a
APP_CPPFLAGS += -std=c++11

View File

@ -0,0 +1,41 @@
// 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 <android/log.h>
#include "android_native_app_glue.h"
#include "animal_generated.h" // Includes "flatbuffers/flatbuffers.h".
void android_main(android_app *) {
flatbuffers::FlatBufferBuilder builder;
auto name = builder.CreateString("Dog");
auto sound = builder.CreateString("Bark");
auto animal_buffer = sample::CreateAnimal(builder, name, sound);
builder.Finish(animal_buffer);
// We now have a FlatBuffer that can be stored on disk or sent over a network.
// ...Code to store on disk or send over a network goes here...
// Instead, we're going to access it immediately, as if we just recieved this.
auto animal = sample::GetAnimal(builder.GetBufferPointer());
assert(animal->name()->str() == "Dog");
assert(animal->sound()->str() == "Bark");
(void)animal; // To silence "Unused Variable" warnings.
__android_log_print(ANDROID_LOG_INFO, "FlatBufferSample",
"FlatBuffer successfully created and verified.");
}

View File

@ -0,0 +1,22 @@
// 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.
namespace sample;
table Animal {
name:string;
sound:string;
}
root_type Animal;

View File

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (c) 2015 Google, Inc.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
-->
<resources>
<string name="app_name">FlatBufferSample</string>
</resources>

View File

@ -0,0 +1,35 @@
#!/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 requires the Android NDK and Android SDK to be installed.
# It also requires an Android device to be connected for installing and
# running the applicaton.
sampledir=$(readlink -fn `dirname $0`)
currentdir=$(readlink -fn `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
# Execute `build_apk.sh` to build and run the android app.
cd android
./gradlew build

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/

View File

@ -0,0 +1,52 @@
#!/bin/bash
#
# 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
cd ../dart/example
# Run `flatc`. Note: This requires you to compile using `cmake` from the
# root `/flatbuffers` directory.
if [ -e ../../flatc ]; then
../../flatc --dart ../../samples/monster.fbs
elif [ -e ../../Debug/flatc ]; then
../../Debug/flatc --dart ../../samples/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 example.dart
# Cleanup temporary files.
git checkout monster_my_game.sample_generated.dart
cd ../../samples

View File

@ -0,0 +1,63 @@
#!/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.
# Go requires a particular layout of files in order to link the necessary
# packages. Copy these files to the respective directores to compile the
# sample.
mkdir -p ${sampledir}/go_gen/src/MyGame/Sample
mkdir -p ${sampledir}/go_gen/src/github.com/google/flatbuffers/go
cp MyGame/Sample/*.go ${sampledir}/go_gen/src/MyGame/Sample/
cp ${sampledir}/../go/* ${sampledir}/go_gen/src/github.com/google/flatbuffers/go
# Export the `GOPATH`, so that `go` will know which directories to search for
# the libraries.
export GOPATH=${sampledir}/go_gen/
# Compile and execute the sample.
go build -o go_sample sample_binary.go
./go_sample
# Clean up the temporary files.
rm -rf MyGame/
rm -rf ${sampledir}/go_gen/
rm go_sample

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

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

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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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.

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;

View File

@ -0,0 +1,880 @@
// 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"
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 {
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 {
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;
};
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 &) FLATBUFFERS_NOEXCEPT;
EquipmentUnion &operator=(const EquipmentUnion &u) FLATBUFFERS_NOEXCEPT
{ 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();
#ifndef FLATBUFFERS_CPP98_STL
template <typename T>
void Set(T&& val) {
using RT = typename std::remove_reference<T>::type;
Reset();
type = EquipmentTraits<typename RT::TableType>::enum_value;
if (type != Equipment_NONE) {
value = new RT(std::forward<T>(val));
}
}
#endif // FLATBUFFERS_CPP98_STL
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() {
memset(static_cast<void *>(this), 0, sizeof(Vec3));
}
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;
flatbuffers::unique_ptr<MyGame::Sample::Vec3> pos;
int16_t mana;
int16_t hp;
std::string name;
std::vector<uint8_t> inventory;
MyGame::Sample::Color color;
std::vector<flatbuffers::unique_ptr<MyGame::Sample::WeaponT>> weapons;
MyGame::Sample::EquipmentUnion equipped;
std::vector<MyGame::Sample::Vec3> path;
MonsterT()
: mana(150),
hp(100),
color(MyGame::Sample::Color_Blue) {
}
};
inline bool operator==(const MonsterT &lhs, const MonsterT &rhs) {
return
(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 == rhs.weapons) &&
(lhs.equipped == rhs.equipped) &&
(lhs.path == rhs.path);
}
inline bool operator!=(const MonsterT &lhs, const MonsterT &rhs) {
return !(lhs == rhs);
}
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) {
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) {
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) {
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) &&
VerifyField<int16_t>(verifier, VT_MANA) &&
VerifyField<int16_t>(verifier, VT_HP) &&
VerifyOffset(verifier, VT_NAME) &&
verifier.VerifyString(name()) &&
VerifyOffset(verifier, VT_INVENTORY) &&
verifier.VerifyVector(inventory()) &&
VerifyField<int8_t>(verifier, VT_COLOR) &&
VerifyOffset(verifier, VT_WEAPONS) &&
verifier.VerifyVector(weapons()) &&
verifier.VerifyVectorOfTables(weapons()) &&
VerifyField<uint8_t>(verifier, VT_EQUIPPED_TYPE) &&
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();
}
MonsterBuilder &operator=(const MonsterBuilder &);
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 = 0,
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 = 0,
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;
WeaponT()
: damage(0) {
}
};
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);
}
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) {
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) &&
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();
}
WeaponBuilder &operator=(const WeaponBuilder &);
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 MonsterT *Monster::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
auto _o = new MonsterT();
UnPackTo(_o, _resolver);
return _o;
}
inline void Monster::UnPackTo(MonsterT *_o, const flatbuffers::resolver_function_t *_resolver) const {
(void)_o;
(void)_resolver;
{ auto _e = pos(); if (_e) _o->pos = flatbuffers::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()); for (flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->inventory[_i] = _e->Get(_i); } } }
{ 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++) { _o->weapons[_i] = flatbuffers::unique_ptr<MyGame::Sample::WeaponT>(_e->Get(_i)->UnPack(_resolver)); } } }
{ 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); } } }
}
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() : 0;
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 WeaponT *Weapon::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
auto _o = new WeaponT();
UnPackTo(_o, _resolver);
return _o;
}
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) {
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 {
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) FLATBUFFERS_NOEXCEPT : 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, 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, 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, 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, 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, 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 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 flatbuffers::unique_ptr<MyGame::Sample::MonsterT> UnPackMonster(
const void *buf,
const flatbuffers::resolver_function_t *res = nullptr) {
return flatbuffers::unique_ptr<MyGame::Sample::MonsterT>(GetMonster(buf)->UnPack(res));
}
inline flatbuffers::unique_ptr<MyGame::Sample::MonsterT> UnPackSizePrefixedMonster(
const void *buf,
const flatbuffers::resolver_function_t *res = nullptr) {
return flatbuffers::unique_ptr<MyGame::Sample::MonsterT>(GetSizePrefixedMonster(buf)->UnPack(res));
}
} // namespace Sample
} // namespace MyGame
#endif // FLATBUFFERS_GENERATED_MONSTER_MYGAME_SAMPLE_H_

View File

@ -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():
return buf_.read_float32_le(pos_ + 0)
def y():
return buf_.read_float32_le(pos_ + 4)
def z():
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():
let o = buf_.flatbuffers_field_struct(pos_, 4)
return if o: MyGame_Sample_Vec3 { buf_, o } else: nil
def mana():
return buf_.flatbuffers_field_int16(pos_, 6, 150)
def hp():
return buf_.flatbuffers_field_int16(pos_, 8, 100)
def name():
return buf_.flatbuffers_field_string(pos_, 10)
def inventory(i:int):
return buf_.read_int8_le(buf_.flatbuffers_field_vector(pos_, 14) + i * 1)
def inventory_length():
return buf_.flatbuffers_field_vector_len(pos_, 14)
def color():
return Color(buf_.flatbuffers_field_int8(pos_, 16, 2))
def weapons(i:int):
return MyGame_Sample_Weapon { buf_, buf_.flatbuffers_indirect(buf_.flatbuffers_field_vector(pos_, 18) + i * 4) }
def weapons_length():
return buf_.flatbuffers_field_vector_len(pos_, 18)
def equipped_type():
return Equipment(buf_.flatbuffers_field_int8(pos_, 20, 0))
def equipped_as_Weapon():
return MyGame_Sample_Weapon { buf_, buf_.flatbuffers_field_table(pos_, 22) }
def path(i:int):
return MyGame_Sample_Vec3 { buf_, buf_.flatbuffers_field_vector(pos_, 24) + i * 12 }
def path_length():
return buf_.flatbuffers_field_vector_len(pos_, 24)
def GetRootAsMonster(buf:string): return Monster { buf, buf.flatbuffers_indirect(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():
return buf_.flatbuffers_field_string(pos_, 4)
def damage():
return buf_.flatbuffers_field_int16(pos_, 6, 0)
def GetRootAsWeapon(buf:string): return Weapon { buf, buf.flatbuffers_indirect(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()

View File

@ -0,0 +1,507 @@
// automatically generated by the FlatBuffers compiler, do not modify
pub mod my_game {
#![allow(dead_code)]
#![allow(unused_imports)]
use std::mem;
use std::marker::PhantomData;
use std::cmp::Ordering;
extern crate flatbuffers;
use self::flatbuffers::EndianScalar;
pub mod sample {
#![allow(dead_code)]
#![allow(unused_imports)]
use std::mem;
use std::marker::PhantomData;
use std::cmp::Ordering;
extern crate flatbuffers;
use self::flatbuffers::EndianScalar;
#[allow(non_camel_case_types)]
#[repr(i8)]
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Color {
Red = 0,
Green = 1,
Blue = 2
}
const ENUM_MIN_COLOR: i8 = 0;
const ENUM_MAX_COLOR: i8 = 2;
impl<'a> flatbuffers::Follow<'a> for Color {
type Inner = Self;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
flatbuffers::read_scalar_at::<Self>(buf, loc)
}
}
impl flatbuffers::EndianScalar for Color {
#[inline]
fn to_little_endian(self) -> Self {
let n = i8::to_le(self as i8);
let p = &n as *const i8 as *const Color;
unsafe { *p }
}
#[inline]
fn from_little_endian(self) -> Self {
let n = i8::from_le(self as i8);
let p = &n as *const i8 as *const Color;
unsafe { *p }
}
}
impl flatbuffers::Push for Color {
type Output = Color;
#[inline]
fn push(&self, dst: &mut [u8], _rest: &[u8]) {
flatbuffers::emplace_scalar::<Color>(dst, *self);
}
}
#[allow(non_camel_case_types)]
const ENUM_VALUES_COLOR:[Color; 3] = [
Color::Red,
Color::Green,
Color::Blue
];
#[allow(non_camel_case_types)]
const ENUM_NAMES_COLOR:[&'static str; 3] = [
"Red",
"Green",
"Blue"
];
pub fn enum_name_color(e: Color) -> &'static str {
let index: usize = e as usize;
ENUM_NAMES_COLOR[index]
}
#[allow(non_camel_case_types)]
#[repr(u8)]
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Equipment {
NONE = 0,
Weapon = 1
}
const ENUM_MIN_EQUIPMENT: u8 = 0;
const ENUM_MAX_EQUIPMENT: u8 = 1;
impl<'a> flatbuffers::Follow<'a> for Equipment {
type Inner = Self;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
flatbuffers::read_scalar_at::<Self>(buf, loc)
}
}
impl flatbuffers::EndianScalar for Equipment {
#[inline]
fn to_little_endian(self) -> Self {
let n = u8::to_le(self as u8);
let p = &n as *const u8 as *const Equipment;
unsafe { *p }
}
#[inline]
fn from_little_endian(self) -> Self {
let n = u8::from_le(self as u8);
let p = &n as *const u8 as *const Equipment;
unsafe { *p }
}
}
impl flatbuffers::Push for Equipment {
type Output = Equipment;
#[inline]
fn push(&self, dst: &mut [u8], _rest: &[u8]) {
flatbuffers::emplace_scalar::<Equipment>(dst, *self);
}
}
#[allow(non_camel_case_types)]
const ENUM_VALUES_EQUIPMENT:[Equipment; 2] = [
Equipment::NONE,
Equipment::Weapon
];
#[allow(non_camel_case_types)]
const ENUM_NAMES_EQUIPMENT:[&'static str; 2] = [
"NONE",
"Weapon"
];
pub fn enum_name_equipment(e: Equipment) -> &'static str {
let index: usize = e as usize;
ENUM_NAMES_EQUIPMENT[index]
}
pub struct EquipmentUnionTableOffset {}
// struct Vec3, aligned to 4
#[repr(C, align(4))]
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Vec3 {
x_: f32,
y_: f32,
z_: f32,
} // pub struct Vec3
impl flatbuffers::SafeSliceAccess for Vec3 {}
impl<'a> flatbuffers::Follow<'a> for Vec3 {
type Inner = &'a Vec3;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
<&'a Vec3>::follow(buf, loc)
//flatbuffers::follow_cast_ref::<Vec3>(buf, loc)
}
}
impl<'a> flatbuffers::Follow<'a> for &'a Vec3 {
type Inner = &'a Vec3;
#[inline]
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]
fn push(&self, dst: &mut [u8], _rest: &[u8]) {
let src = unsafe {
::std::slice::from_raw_parts(self as *const Vec3 as *const u8, Self::size())
};
dst.copy_from_slice(src);
}
}
impl<'b> flatbuffers::Push for &'b Vec3 {
type Output = Vec3;
#[inline]
fn push(&self, dst: &mut [u8], _rest: &[u8]) {
let src = unsafe {
::std::slice::from_raw_parts(*self as *const Vec3 as *const u8, Self::size())
};
dst.copy_from_slice(src);
}
}
impl Vec3 {
pub fn new<'a>(_x: f32, _y: f32, _z: f32) -> Self {
Vec3 {
x_: _x.to_little_endian(),
y_: _y.to_little_endian(),
z_: _z.to_little_endian(),
}
}
pub fn x<'a>(&'a self) -> f32 {
self.x_.from_little_endian()
}
pub fn y<'a>(&'a self) -> f32 {
self.y_.from_little_endian()
}
pub fn z<'a>(&'a self) -> f32 {
self.z_.from_little_endian()
}
}
pub enum MonsterOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Monster<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for Monster<'a> {
type Inner = Monster<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> Monster<'a> {
#[inline]
pub 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>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args MonsterArgs<'args>) -> flatbuffers::WIPOffset<Monster<'bldr>> {
let mut builder = MonsterBuilder::new(_fbb);
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 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;
#[inline]
pub fn pos(&'a self) -> Option<&'a Vec3> {
self._tab.get::<Vec3>(Monster::VT_POS, None)
}
#[inline]
pub fn mana(&'a self) -> i16 {
self._tab.get::<i16>(Monster::VT_MANA, Some(150)).unwrap()
}
#[inline]
pub fn hp(&'a self) -> i16 {
self._tab.get::<i16>(Monster::VT_HP, Some(100)).unwrap()
}
#[inline]
pub fn name(&'a self) -> Option<&'a str> {
self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(Monster::VT_NAME, None)
}
#[inline]
pub fn inventory(&'a self) -> Option<&'a [u8]> {
self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, u8>>>(Monster::VT_INVENTORY, None).map(|v| v.safe_slice())
}
#[inline]
pub fn color(&'a self) -> Color {
self._tab.get::<Color>(Monster::VT_COLOR, Some(Color::Blue)).unwrap()
}
#[inline]
pub fn weapons(&'a self) -> Option<flatbuffers::Vector<flatbuffers::ForwardsUOffset<Weapon<'a>>>> {
self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<flatbuffers::ForwardsUOffset<Weapon<'a>>>>>(Monster::VT_WEAPONS, None)
}
#[inline]
pub fn equipped_type(&'a self) -> Equipment {
self._tab.get::<Equipment>(Monster::VT_EQUIPPED_TYPE, Some(Equipment::NONE)).unwrap()
}
#[inline]
pub fn equipped(&'a self) -> Option<flatbuffers::Table<'a>> {
self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Table<'a>>>(Monster::VT_EQUIPPED, None)
}
#[inline]
#[allow(non_snake_case)]
pub fn equipped_as_weapon(&'a self) -> Option<Weapon> {
if self.equipped_type() == Equipment::Weapon {
self.equipped().map(|u| Weapon::init_from_table(u))
} else {
None
}
}
}
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>>,
}
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,
}
}
}
pub struct MonsterBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> MonsterBuilder<'a, 'b> {
#[inline]
pub fn add_pos(&mut self, pos: &'b 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 new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> MonsterBuilder<'a, 'b> {
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())
}
}
pub enum WeaponOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Weapon<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for Weapon<'a> {
type Inner = Weapon<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self {
_tab: flatbuffers::Table { buf: buf, loc: loc },
}
}
}
impl<'a> Weapon<'a> {
#[inline]
pub 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>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
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 const VT_NAME: flatbuffers::VOffsetT = 4;
pub const VT_DAMAGE: flatbuffers::VOffsetT = 6;
#[inline]
pub fn name(&'a self) -> Option<&'a str> {
self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(Weapon::VT_NAME, None)
}
#[inline]
pub fn damage(&'a self) -> i16 {
self._tab.get::<i16>(Weapon::VT_DAMAGE, Some(0)).unwrap()
}
}
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> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> WeaponBuilder<'a, 'b> {
#[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>) -> WeaponBuilder<'a, 'b> {
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())
}
}
#[inline]
pub fn get_root_as_monster<'a>(buf: &'a [u8]) -> Monster<'a> {
flatbuffers::get_root::<Monster<'a>>(buf)
}
#[inline]
pub fn get_size_prefixed_root_as_monster<'a>(buf: &'a [u8]) -> Monster<'a> {
flatbuffers::get_size_prefixed_root::<Monster<'a>>(buf)
}
#[inline]
pub fn finish_monster_buffer<'a, 'b>(
fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
root: flatbuffers::WIPOffset<Monster<'a>>) {
fbb.finish(root, None);
}
#[inline]
pub fn finish_size_prefixed_monster_buffer<'a, 'b>(fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>, root: flatbuffers::WIPOffset<Monster<'a>>) {
fbb.finish_size_prefixed(root, None);
}
} // pub mod Sample
} // pub mod MyGame

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
}
}

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/

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

View File

@ -0,0 +1,77 @@
/*
* 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((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 (!GenerateText(parser1, parser1.builder_.GetBufferPointer(), &jsongen1)) {
printf("Couldn't serialize parsed data to JSON!\n");
return 1;
}
std::string jsongen2;
if (!GenerateText(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");
}

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");
}

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 "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 + ".")
}
}

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)
// 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!"

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!")

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(10)
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(2)
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() == '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 xrange(monster.InventoryLength()):
assert monster.Inventory(i) == i
# Get and test the `weapons` FlatBuffer `vector` of `table`s.
expected_weapon_names = ['Sword', 'Axe']
expected_weapon_damages = [3, 5]
for i in xrange(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() == "Axe"
assert union_weapon.Damage() == 5
print 'The FlatBuffer was successfully created and verified!'
if __name__ == '__main__':
main()

View File

@ -0,0 +1,155 @@
/*
* 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
#[path = "./monster_generated.rs"]
mod monster_generated;
pub use monster_generated::my_game::sample::{get_root_as_monster,
Color, Equipment,
Monster, MonsterArgs,
Vec3,
Weapon, WeaponArgs};
// Example how to use FlatBuffers to create and read binary buffers.
fn main() {
// Build up a serialized buffer algorithmically.
// Initialize it with a capacity of 1024 bytes.
let mut builder = flatbuffers::FlatBufferBuilder::new_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 demononstrated 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 = get_root_as_monster(buf);
// 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();
// Note that this vector is returned as a slice, because direct access for
// this type, a u8 vector, is safe on all platforms:
let third_item = inv[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!");
}

View File

@ -0,0 +1,68 @@
// THIS IS JUST TO SHOW THE CODE, PLEASE DO IMPORT FLATBUFFERS WITH SPM..
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"]
let 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 pos = builder.create(struct: MyGame.Sample.createVec3(x: 1, y: 2, z: 3), type: Vec3.self)
let orc = Monster.createMonster(builder,
offsetOfPos: pos,
hp: 300,
offsetOfName: name,
vectorOfInventory: inventoryOffset,
color: .red,
vectorOfWeapons: weaponsOffset,
equippedType: .weapon,
offsetOfEquipped: axe)
builder.finish(offset: orc)
var buf = builder.sizedByteArray
var monster = Monster.getRootAsMonster(bb: ByteBuffer(bytes: buf))
assert(monster.mana == 150)
assert(monster.hp == 300)
assert(monster.name == "Orc")
assert(monster.color == MyGame.Sample.Color.red)
assert(monster.pos != 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")
}

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 (!GenerateText(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");
}

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

View File

@ -0,0 +1,106 @@
/*
* 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 `javascript_sample.sh` script.
var assert = require('assert');
var flatbuffers = require('../js/flatbuffers').flatbuffers;
var MyGame = require('./monster_generated').MyGame;
// Example how to use FlatBuffers to create and read binary buffers.
function main() {
var builder = new flatbuffers.Builder(0);
// Create some weapons for our Monster ('Sword' and 'Axe').
var weaponOne = builder.createString('Sword');
var weaponTwo = builder.createString('Axe');
MyGame.Sample.Weapon.startWeapon(builder);
MyGame.Sample.Weapon.addName(builder, weaponOne);
MyGame.Sample.Weapon.addDamage(builder, 3);
var sword = MyGame.Sample.Weapon.endWeapon(builder);
MyGame.Sample.Weapon.startWeapon(builder);
MyGame.Sample.Weapon.addName(builder, weaponTwo);
MyGame.Sample.Weapon.addDamage(builder, 5);
var axe = MyGame.Sample.Weapon.endWeapon(builder);
// Serialize the FlatBuffer data.
var name = builder.createString('Orc');
var treasure = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var inv = MyGame.Sample.Monster.createInventoryVector(builder, treasure);
var weaps = [sword, axe];
var weapons = MyGame.Sample.Monster.createWeaponsVector(builder, weaps);
var 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.addColor(builder, MyGame.Sample.Color.Red)
MyGame.Sample.Monster.addName(builder, name);
MyGame.Sample.Monster.addInventory(builder, inv);
MyGame.Sample.Monster.addWeapons(builder, weapons);
MyGame.Sample.Monster.addEquippedType(builder, MyGame.Sample.Equipment.Weapon);
MyGame.Sample.Monster.addEquipped(builder, weaps[1]);
var orc = MyGame.Sample.Monster.endMonster(builder);
builder.finish(orc); // You may also call 'MyGame.Example.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.
var buf = builder.dataBuffer();
// Get access to the root:
var monster = MyGame.Sample.Monster.getRootAsMonster(buf);
// Note: We did not set the `mana` field explicitly, so we get back the default value.
assert.equal(monster.mana(), 150);
assert.equal(monster.hp(), 300);
assert.equal(monster.name(), 'Orc');
assert.equal(monster.color(), MyGame.Sample.Color.Red);
assert.equal(monster.pos().x(), 1.0);
assert.equal(monster.pos().y(), 2.0);
assert.equal(monster.pos().z(), 3.0);
// Get and test the `inventory` FlatBuffer `vector`.
for (var i = 0; i < monster.inventoryLength(); i++) {
assert.equal(monster.inventory(i), i);
}
// Get and test the `weapons` FlatBuffer `vector` of `table`s.
var expectedWeaponNames = ['Sword', 'Axe'];
var expectedWeaponDamages = [3, 5];
for (var i = 0; i < monster.weaponsLength(); i++) {
assert.equal(monster.weapons(i).name(), expectedWeaponNames[i]);
assert.equal(monster.weapons(i).damage(), expectedWeaponDamages[i]);
}
// Get and test the `equipped` FlatBuffer `union`.
assert.equal(monster.equippedType(), MyGame.Sample.Equipment.Weapon);
assert.equal(monster.equipped(new MyGame.Sample.Weapon()).name(), 'Axe');
assert.equal(monster.equipped(new MyGame.Sample.Weapon()).damage(), 5);
console.log('The FlatBuffer was successfully created and verified!');
}
main();