### Build and Test FlatBuffers with Bazel Source: https://flatbuffers.dev/building Set up Bazelisk, install necessary dependencies like Clang and Swift SDK, and then build and test the entire project using Bazel. This example includes downloading Bazelisk, installing clang, downloading a specific Swift version, and configuring the environment for Bazel commands. ```bash curl -sL --fail https://github.com/bazelbuild/bazelisk/releases/download/v1.25.0/bazelisk-linux-amd64 -o bazelisk && chmod +x bazelisk sudo apt install -y clang SWIFT_VERSION="6.0.3" curl -L https://download.swift.org/swift-${SWIFT_VERSION}-release/debian12/swift-${SWIFT_VERSION}-RELEASE/swift-${SWIFT_VERSION}-RELEASE-debian12.tar.gz | tar xz CC=clang PATH=$PATH:$(pwd)/swift-${SWIFT_VERSION}-RELEASE-debian12/usr/bin bazel build //... CC=clang PATH=$PATH:$(pwd)/swift-${SWIFT_VERSION}-RELEASE-debian12/usr/bin bazel test //... ``` -------------------------------- ### Flatc Conformity Check Example Source: https://flatbuffers.dev/evolution An example command to check if 'schema_v2.fbs' is properly evolved from 'schema_v1.fbs'. ```bash flatc --conform schema_v1.fbs schema_v2.fbs ``` -------------------------------- ### Example: Annotating Binary Data Source: https://flatbuffers.dev/annotation This example demonstrates how to annotate a specific binary file using its corresponding schema. It shows the command to run within the test directory and the expected output file. ```bash cd tests/annotated_binary ../../flatc --annotate annotated_binary.fbs -- annotated_binary.bin ``` -------------------------------- ### Install FlatBuffers with VCPKG Source: https://flatbuffers.dev/building Follow these steps to clone the vcpkg repository, bootstrap it, integrate it with your system, and then install the FlatBuffers port. This method is suitable for C++ projects. ```bash git clone https://github.com/Microsoft/vcpkg.git cd vcpkg ./bootstrap-vcpkg.sh ./vcpkg integrate install ./vcpkg install flatbuffers ``` -------------------------------- ### Install FlatBuffers with Conan Source: https://flatbuffers.dev/building Use this command to download and install the FlatBuffers package via the Conan dependency manager. Ensure you have Conan installed and configured. ```bash conan install --requires="flatbuffers/[*]" --build=missing ``` -------------------------------- ### Install MkDocs Dependencies Source: https://flatbuffers.dev/contributing Install the necessary Python packages for MkDocs and its Material theme to build and serve documentation locally. Ensure you have Python and pip installed. ```bash pip install mkdocs-material pip install mkdocs-redirects ``` -------------------------------- ### Get Data Using Preconstructed Object in C# Source: https://flatbuffers.dev/languages/c_sharp Demonstrates how to retrieve data by passing a preconstructed object to a method, which is prefixed with 'Get'. This can be a performance optimization. ```csharp // property var pos = monster.Pos; // method filling a preconstructed object var preconstructedPos = new Vec3(); monster.GetPos(preconstructedPos); ``` -------------------------------- ### Annotated Binary Section: VTable Example Source: https://flatbuffers.dev/annotation This example illustrates the structure of a `vtable` binary section associated with a user-defined FlatBuffer table. It details the offset, raw bytes, data type, value, and notes for each entry. ```text vtable (AnnotatedBinary.Bar): +0x00A0 | 08 00 | uint16_t | 0x0008 (8) | size of this vtable +0x00A2 | 13 00 | uint16_t | 0x0013 (19) | size of referring table +0x00A4 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `a` (id: 0) +0x00A6 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) ``` -------------------------------- ### Example: Creating Binary from JSON Source: https://flatbuffers.dev/annotation This command shows how to generate a FlatBuffer binary file from a JSON data file using a schema. This is a prerequisite for creating the annotated binary file. ```bash ../../flatc -b annotated_binary.fbs annotated_binary.json ``` -------------------------------- ### Create Weapons using Builder Pattern (C#) Source: https://flatbuffers.dev/tutorial Demonstrates creating Weapon objects using a builder pattern with start, add, and end methods. ```csharp // start creating the weapon by calling startWeapon let weapon1Start = Weapon.startWeapon(&builder) Weapon.add(name: weapon1Name, &builder) Weapon.add(damage: 3, &builder) // end the object by passing the start point for the weapon 1 let sword = Weapon.endWeapon(&builder, start: weapon1Start) let weapon2Start = Weapon.startWeapon(&builder) Weapon.add(name: weapon2Name, &builder) Weapon.add(damage: 5, &builder) let axe = Weapon.endWeapon(&builder, start: weapon2Start) ``` -------------------------------- ### PHP Autoloader and Reading a FlatBuffer Source: https://flatbuffers.dev/languages/php This example demonstrates how to set up a PSR autoloader for FlatBuffers and generated PHP classes, and then read a FlatBuffer binary file. Ensure the FlatBuffers library and your generated code are accessible via the autoloader. ```php // It is recommended that you use PSR autoload when using FlatBuffers in PHP. // Here is an example: function __autoload($class_name) { // The last segment of the class name matches the file name. $class = substr($class_name, strrpos($class_name, "\\") + 1); $root_dir = join(DIRECTORY_SEPARATOR, array(dirname(dirname(__FILE__)))); // `flatbuffers` root. // Contains the `*.php` files for the FlatBuffers library and the `flatc` generated files. $paths = array(join(DIRECTORY_SEPARATOR, array($root_dir, "php")), join(DIRECTORY_SEPARATOR, array($root_dir, "tests", "MyGame", "Example"))); foreach ($paths as $path) { $file = join(DIRECTORY_SEPARATOR, array($path, $class . ".php")); if (file_exists($file)) { require($file); break; } } } // Read the contents of the FlatBuffer binary file. $filename = "monster.dat"; $handle = fopen($filename, "rb"); $contents = fread($handle, filesize($filename)); fclose($handle); // Pass the contents to `GetRootAsMonster`. $monster = \MyGame\Example\Monster::GetRootAsMonster($contents); ``` -------------------------------- ### Annotation Example: Binary Region Source: https://flatbuffers.dev/annotation This example shows a single binary region within a `vtable` section. It highlights the offset, raw bytes in little-endian, the interpreted data type, the big-endian value with its decimal representation, and a descriptive note. ```text vtable (AnnotatedBinary.Bar): +0x00A0 | 08 00 | uint16_t | 0x0008 (8) | size of this vtable ``` -------------------------------- ### gRPC Client for FlatBuffers in C++ Source: https://flatbuffers.dev/languages/cpp Implements a gRPC client using FlatBuffers for communication. This example demonstrates making both a single unary call (SayHello) and a server-streaming call (SayManyHellos). Ensure the Greeter service and its stub are correctly defined. ```cpp void SayManyHellos(const std::string& name, int num_greetings, std::function callback) { flatbuffers::grpc::MessageBuilder mb; auto name_offset = mb.CreateString(name); auto request_offset = CreateManyHellosRequest(mb, name_offset, num_greetings); mb.Finish(request_offset); auto request_msg = mb.ReleaseMessage(); flatbuffers::grpc::Message response_msg; grpc::ClientContext context; auto stream = stub_->SayManyHellos(&context, request_msg); while (stream->Read(&response_msg)) { const HelloReply* response = response_msg.GetRoot(); callback(response->message()->str()); } auto status = stream->Finish(); if (!status.ok()) { std::cerr << status.error_code() << ": " << status.error_message() << std::endl; callback("RPC failed"); } } private: std::unique_ptr stub_; }; int main(int argc, char** argv) { std::string server_address("localhost:50051"); auto channel = grpc::CreateChannel(server_address, grpc::InsecureChannelCredentials()); GreeterClient greeter(channel); std::string name("world"); std::string message = greeter.SayHello(name); std::cerr << "Greeter received: " << message << std::endl; int num_greetings = 10; greeter.SayManyHellos(name, num_greetings, [](const std::string& message) { std::cerr << "Greeter received: " << message << std::endl; }); return 0; } ``` -------------------------------- ### Build FlatBuffer with Error Propagation Source: https://flatbuffers.dev/languages/rust Example of building a FlatBuffer using fallible `try_*` methods, demonstrating error propagation with a generic `Allocator`. ```rust fn build( builder: &mut FlatBufferBuilder, ) -> Result<(), A::Error> { let name = builder.try_create_string("Orc")?; let inventory = builder.try_create_vector(&[0u8, 1, 2, 3, 4])?; let table_start = builder.start_table(); builder.try_push_slot_always(Monster::VT_NAME, name)?; builder.try_push_slot_always(Monster::VT_INVENTORY, inventory)?; builder.try_push_slot(Monster::VT_HP, 80i16, 100)?; let root = builder.try_end_table(table_start)?; builder.try_finish(root, None)?; Ok(()) } ``` -------------------------------- ### FlatBuffers Root Integer Encoding Example Source: https://flatbuffers.dev/internals Demonstrates the encoding of a simple integer value as the root of a FlatBuffers buffer. Shows the order of value, type, and root byte width. ```text uint8_t 13, 4, 1 // Value, type, root byte width. ``` -------------------------------- ### Verify FlatBuffers Binaries with SLSA Source: https://flatbuffers.dev/building Use the slsa-verifier tool to confirm the integrity of downloaded FlatBuffers binaries against their SLSA provenance. Ensure the verification tool is installed and you have the artifact and attestation files. ```bash $ slsa-verifier -artifact-path -provenance attestation.intoto.jsonl -source github.com/google/flatbuffers -tag PASSED: Verified SLSA provenance ``` -------------------------------- ### FlatBuffers Map Encoding Example Source: https://flatbuffers.dev/internals Illustrates the byte-level encoding of a FlatBuffers map with keys 'foo' and 'bar' and corresponding values. Shows the structure of key and value vectors, including offsets, byte widths, and types. ```text 0 : uint8_t 'b', 'a', 'r', 0 4 : uint8_t 'f', 'o', 'o', 0 8 : uint8_t 2 // key vector of size 2 // key vector offset points here 9 : uint8_t 9, 6 // offsets to bar_key and foo_key 11: uint8_t 2, 1 // offset to key vector, and its byte width 13: uint8_t 2 // value vector of size // value vector offset points here 14: uint8_t 14, 13 // values 16: uint8_t 4, 4 // types ``` -------------------------------- ### FlatBuffers Encoding Example Source: https://flatbuffers.dev/internals Illustrates the binary buffer structure resulting from a given JSON object, showing offsets, vtable, root table, and string data. ```plaintext // Start of the buffer: uint32_t 20 // Offset to the root table. // Start of the vtable. Not shared in this example, but could be: uint16_t 16 // Size of table, starting from here. uint16_t 22 // Size of object inline data. uint16_t 4, 0, 20, 16, 0, 0 // Offsets to fields from start of (root) table, 0 for not present. // Start of the root table: int32_t 16 // Offset to vtable used (default negative direction) float 1, 2, 3 // the Vec3 struct, inline. uint32_t 8 // Offset to the name string. int16_t 50 // hp field. int16_t 0 // Padding for alignment. // Start of name string: uint32_t 4 // Length of string. int8_t 'f', 'r', 'e', 'd', 0, 0, 0, 0 // Text + 0 termination + padding. ``` -------------------------------- ### Create Monster in Rust Source: https://flatbuffers.dev/tutorial Use `start()` and `end()` methods on the builder to construct a monster object. Ensure all fields are set before ending. ```rust use flatbuffers::Builder; use MyGame_Sample::*; fn main() { let mut b = Builder::with_capacity(1024); // Serialize a name for our monster, called "Orc". let name = b.create_string("Orc"); // Create inventory items, then serialize them. let item1 = MyGame_Sample::Item::create(&b, 1, 2, "Sword"); let item2 = MyGame_Sample::Item::create(&b, 5, 3, "Shield"); // Create a FlatBuffer table with the items in it. let inv = MyGame_Sample::Item::create_inventory_vector(&b, &[item1, item2]); // Create a FlatBuffer table with weapons in it. let weapon1 = MyGame_Sample::Weapon::create(&b, 1, item1); let weapon2 = MyGame_Sample::Weapon::create(&b, 2, item2); let weapons = MyGame_Sample::Weapon::create_weapons_vector(&b, &[weapon1, weapon2]); // Create a FlatBuffer table with a weapon in it. let axe = MyGame_Sample::Weapon::create(&b, 3, item1); // Create our monster using `start()` and `end()`. let orc = MyGame_Sample::MonsterBuilder { b: &mut b, } .start() .add_pos(MyGame_Sample::create_vec3(&b, 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(axe) .add_path(b.create_string("path/to/monster")) .end(); b.finish(orc, None); } ``` -------------------------------- ### Create Monster in Lua Source: https://flatbuffers.dev/tutorial Use `Start()` and `End()` to construct a monster object. Ensure all fields are set before ending. ```lua local builder = flatbuffers.Builder.new(1024) -- Serialize a name for our monster, called 'orc' local name = builder:CreateString("Orc") -- Create inventory items, then serialize them. local item1 = vec3.CreateVec3(builder, 1, 2, "Sword") local item2 = vec3.CreateVec3(builder, 5, 3, "Shield") -- Create a FlatBuffer table with the items in it. local inv = vec3.CreateInventoryVector(builder, {item1, item2}) -- Create a FlatBuffer table with weapons in it. local weapon1 = vec3.CreateWeapon(builder, 1, item1) local weapon2 = vec3.CreateWeapon(builder, 2, item2) local weapons = vec3.CreateWeaponsVector(builder, {weapon1, weapon2}) -- Create a FlatBuffer table with a weapon in it. local axe = vec3.CreateWeapon(builder, 3, item1) -- Create our monster by using Start() and End() 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 path = builder:CreateString("path/to/monster") monster.AddPath(builder, path) local orc = monster.End(builder) builder.Finish(orc) ``` -------------------------------- ### gRPC Client Implementation with FlatBuffers Source: https://flatbuffers.dev/languages/cpp Example C++ code for a gRPC client that uses FlatBuffers for request and response serialization. It demonstrates making a unary RPC call. ```cpp #include #include #include #include #include "greeter.grpc.fb.h" #include "greeter_generated.h" class GreeterClient { public: GreeterClient(std::shared_ptr channel) : stub_(Greeter::NewStub(channel)) {} std::string SayHello(const std::string& name) { flatbuffers::grpc::MessageBuilder mb; auto name_offset = mb.CreateString(name); auto request_offset = CreateHelloRequest(mb, name_offset); mb.Finish(request_offset); auto request_msg = mb.ReleaseMessage(); flatbuffers::grpc::Message response_msg; grpc::ClientContext context; auto status = stub_->SayHello(&context, request_msg, &response_msg); if (status.ok()) { const HelloReply* response = response_msg.GetRoot(); return response->message()->str(); } } ``` -------------------------------- ### Create Weapons using Builder Pattern (Lua) Source: https://flatbuffers.dev/tutorial Uses a builder pattern with explicit start and end calls to create Weapon objects. ```lua -- 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) ``` -------------------------------- ### gRPC Server Implementation with FlatBuffers Source: https://flatbuffers.dev/languages/cpp Example C++ code for a gRPC server that uses FlatBuffers for request and response serialization. It handles both unary and server-streaming RPC calls. ```cpp #include #include #include #include #include "greeter.grpc.fb.h" #include "greeter_generated.h" class GreeterServiceImpl final : public Greeter::Service { virtual grpc::Status SayHello( grpc::ServerContext* context, const flatbuffers::grpc::Message* request_msg, flatbuffers::grpc::Message* response_msg) override { flatbuffers::grpc::MessageBuilder mb_; // We call GetRoot to "parse" the message. Verification is already // performed by default. See the notes below for more details. const HelloRequest* request = request_msg->GetRoot(); // Fields are retrieved as usual with FlatBuffers const std::string& name = request->name()->str(); // `flatbuffers::grpc::MessageBuilder` is a `FlatBufferBuilder` with a // special allocator for efficient gRPC buffer transfer, but otherwise // usage is the same as usual. auto msg_offset = mb_.CreateString("Hello, " + name); auto hello_offset = CreateHelloReply(mb_, msg_offset); mb_.Finish(hello_offset); // The `ReleaseMessage()` function detaches the message from the // builder, so we can transfer the resopnse to gRPC while simultaneously // detaching that memory buffer from the builer. *response_msg = mb_.ReleaseMessage(); assert(response_msg->Verify()); // Return an OK status. return grpc::Status::OK; } virtual grpc::Status SayManyHellos( grpc::ServerContext* context, const flatbuffers::grpc::Message* request_msg, grpc::ServerWriter>* writer) override { // The streaming usage below is simply a combination of standard gRPC // streaming with the FlatBuffers usage shown above. const ManyHellosRequest* request = request_msg->GetRoot(); const std::string& name = request->name()->str(); int num_greetings = request->num_greetings(); for (int i = 0; i < num_greetings; i++) { auto msg_offset = mb_.CreateString("Many hellos, " + name); auto hello_offset = CreateHelloReply(mb_, msg_offset); mb_.Finish(hello_offset); writer->Write(mb_.ReleaseMessage()); } return grpc::Status::OK; } flatbuffers::grpc::MessageBuilder mb_; }; void RunServer() { std::string server_address("0.0.0.0:50051"); GreeterServiceImpl service; grpc::ServerBuilder builder; builder.AddListeningPort(server_address, grpc::InsecureServerCredentials()); builder.RegisterService(&service); std::unique_ptr server(builder.BuildAndStart()); std::cerr << "Server listening on " << server_address << std::endl; server->Wait(); } int main(int argc, const char* argv[]) { RunServer(); return 0; } ``` -------------------------------- ### Serve FlatBuffers Documentation Locally Source: https://flatbuffers.dev/contributing Run the MkDocs serve command from the root directory of the FlatBuffers repository to build and serve the documentation locally. This command will watch for changes and update the served pages automatically. ```bash mkdocs serve -f docs/mkdocs.yml ``` -------------------------------- ### Get Root Object (Swift) Source: https://flatbuffers.dev/tutorial Use `getCheckedRoot` or `getRoot` to get an accessor to the root object inside the buffer. The data should be in a `ByteBuffer`. ```swift // create a ByteBuffer(:) from an [UInt8] or Data() var buf = // Get your data // Get an accessor to the root object inside the buffer. let monster: Monster = try! getCheckedRoot(byteBuffer: &byteBuffer) // let monster: Monster = getRoot(byteBuffer: &byteBuffer) ``` -------------------------------- ### Get Root Object (Rust) Source: https://flatbuffers.dev/tutorial Use `root_as_monster` to get an accessor to the root object inside the buffer. Ensure the buffer is a `&[u8]`. ```rust let buf = /* the data you just read, in a &[u8] */ // Get an accessor to the root object inside the buffer. let monster = root_as_monster(buf).unwrap(); ``` -------------------------------- ### FlatBuffers Schema Definition Example Source: https://flatbuffers.dev/schema An example FlatBuffers schema defining namespaces, attributes, enums, unions, structs, tables, and the root type. ```flatbuffers namespace MyGame; attribute "priority"; enum Color : byte { Red = 1, Green, Blue } union Any { Monster, Weapon, Pickup } struct Vec3 { x:float; y:float; z:float; } table Monster { pos:Vec3; mana:short = 150; hp:short = 100; name:string; friendly:bool = false (deprecated, priority: 1); inventory:[ubyte]; color:Color = Blue; test:Any; } table Weapon {} table Pickup {} root_type Monster; ``` -------------------------------- ### Create Weapons using Sample API (C#) Source: https://flatbuffers.dev/tutorial Shows how to create Weapon objects using the generated Sample API for adding fields. ```csharp // Create the first `Weapon` ('Sword'). MyGame.Sample.Weapon.startWeapon(builder); MyGame.Sample.Weapon.addName(builder, weaponOne); MyGame.Sample.Weapon.addDamage(builder, 3); let sword = MyGame.Sample.Weapon.endWeapon(builder); // Create the second `Weapon` ('Axe'). MyGame.Sample.Weapon.startWeapon(builder); MyGame.Sample.Weapon.addName(builder, weaponTwo); MyGame.Sample.Weapon.addDamage(builder, 5); let axe = MyGame.Sample.Weapon.endWeapon(builder); ``` -------------------------------- ### Create Weapons using Sample API (Java) Source: https://flatbuffers.dev/tutorial Shows how to create Weapon objects using the generated Sample API for adding fields. ```java // Create the first `Weapon` ('Sword'). MyGame.Sample.Weapon.startWeapon(builder); MyGame.Sample.Weapon.addName(builder, weaponOne); MyGame.Sample.Weapon.addDamage(builder, 3); var sword = MyGame.Sample.Weapon.endWeapon(builder); // Create the second `Weapon` ('Axe'). MyGame.Sample.Weapon.startWeapon(builder); MyGame.Sample.Weapon.addName(builder, weaponTwo); MyGame.Sample.Weapon.addDamage(builder, 5); var axe = MyGame.Sample.Weapon.endWeapon(builder); ``` -------------------------------- ### Get Root Object (Python) Source: https://flatbuffers.dev/tutorial Use `GetRootAs` to get an accessor to the root object inside the buffer. The offset `0` is typical for most buffers. ```python monster = MyGame.Sample.Monster.Monster.GetRootAs(buf, 0) ``` -------------------------------- ### Create Weapons using Sample API (Python) Source: https://flatbuffers.dev/tutorial Demonstrates creating Weapon objects using the generated Sample API for adding fields. ```python # Create the first `Weapon` ('Sword'). MyGame.Sample.Weapon.Start(builder) MyGame.Sample.Weapon.AddName(builder, weapon_one) MyGame.Sample.Weapon.AddDamage(builder, 3) sword = MyGame.Sample.Weapon.End(builder) # Create the second `Weapon` ('Axe'). MyGame.Sample.Weapon.Start(builder) MyGame.Sample.Weapon.AddName(builder, weapon_two) MyGame.Sample.Weapon.AddDamage(builder, 5) axe = MyGame.Sample.Weapon.End(builder) ``` -------------------------------- ### Create Weapons using Helper Functions (Go) Source: https://flatbuffers.dev/tutorial Demonstrates creating Weapon objects using generated helper functions for adding fields. ```go // Create the first `Weapon` ("Sword"). sample.WeaponStart(builder) sample.WeaponAddName(builder, weaponOne) sample.WeaponAddDamage(builder, 3) sword := sample.WeaponEnd(builder) // Create the second `Weapon` ("Axe"). sample.WeaponStart(builder) sample.WeaponAddName(builder, weaponTwo) sample.WeaponAddDamage(builder, 5) axe := sample.WeaponEnd(builder) ``` -------------------------------- ### Go: Initialize FlatBufferBuilder Source: https://flatbuffers.dev/tutorial Constructs a FlatBufferBuilder with a 1024 byte backing array in Go. ```go // Construct a Builder with 1024 byte backing array. var builder = flatbuffers.NewBuilder(1024) ``` -------------------------------- ### Get Sized Copy (Lua) Source: https://flatbuffers.dev/tutorial This returns the generated buffer as a string. ```lua local bufAsString = builder:Output() ``` -------------------------------- ### Create Monster Inventory and Path Vectors in Lua Source: https://flatbuffers.dev/tutorial Shows how to create inventory and path vectors using Lua. Prepending bytes for inventory and vectors in reverse order for path are key. ```lua -- 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 path locations. -- Note: Since we prepend the data, prepend them in reverse order. monster.StartPathVector(builder, 2) vec3.CreateVec3(builder, 1.0, 2.0, 3.0) vec3.CreateVec3(builder, 4.0, 5.0, 6.0) local path = builder:EndVector(2) ``` -------------------------------- ### Define FlatBuffers Schema Source: https://flatbuffers.dev/quick_start Example of a simple FlatBuffers schema definition for a 'Monster' table. ```fbs table Monster { name:string; health:int; } root_type Monster; ``` -------------------------------- ### PHP: Initialize FlatBufferBuilder Source: https://flatbuffers.dev/tutorial Constructs a FlatBufferBuilder with a 1024 byte backing array in PHP. ```php // Construct a Builder with 1024 byte backing array. $builder = new Google\FlatBuffers\FlatbufferBuilder(1024); ``` -------------------------------- ### Access Root Object (TypeScript) Source: https://flatbuffers.dev/tutorial Get the root object accessor from a bytearray object. ```typescript buf = /* the data you just read, in an object of type "bytearray" */ ``` -------------------------------- ### Get Uint8Array (JavaScript) Source: https://flatbuffers.dev/tutorial Retrieve the finished buffer as a Uint8Array. This must be called after `finish()`. ```javascript // This must be called after `finish()`. let buf = builder.asUint8Array(); // Of type `Uint8Array`. ``` -------------------------------- ### Get Buffer as Uint8Array (JavaScript) Source: https://flatbuffers.dev/tutorial This must be called after `finish()`. `asUint8Array()` returns the buffer as a `Uint8Array`. ```javascript // This must be called after `finish()`. var buf = builder.asUint8Array(); // Of type `Uint8Array`. ``` -------------------------------- ### Lobster: Initialize FlatBufferBuilder Source: https://flatbuffers.dev/tutorial Constructs a FlatBufferBuilder with a 1024 byte backing array in Lobster. ```lobster // Construct a Builder with 1024 byte backing array. let builder = flatbuffers_builder {} ``` -------------------------------- ### Build FlatBuffers with Make (Unix) Source: https://flatbuffers.dev/building Build the project using 'make' with parallel job execution after CMake configuration on Unix-like systems. ```bash make -j ``` -------------------------------- ### Get Serialized Buffer Pointer Source: https://flatbuffers.dev/quick_start C++ code snippet to retrieve a pointer to the generated FlatBuffer. ```cpp // Get a pointer to the flatbuffer. const uint8_t* flatbuffer = builder.GetBufferPointer(); ``` -------------------------------- ### Access Root Object (Kotlin) Source: https://flatbuffers.dev/tutorial Wrap the byte array in a `java.nio.ByteBuffer` to get an accessor for the root object. ```kotlin val bytes = /* the data you just read */ val buf = java.nio.ByteBuffer.wrap(bytes) // Get an accessor to the root object inside the buffer. Monster monster = Monster.getRootAsMonster(buf) ``` -------------------------------- ### Create Monster in Go Source: https://flatbuffers.dev/tutorial Use `MonsterStart()` and `MonsterEnd()` to construct a monster object. Ensure all fields are set before ending. ```go package main import ( flatbuffers "github.com/google/flatbuffers/go" sample "samples/monster/go" ) func main() { builder := flatbuffers.NewBuilder(1024) // Serialize a name for our monster, called "Orc". name := builder.CreateString("Orc") // Create inventory items, then serialize them. item1 := sample.CreateItem(builder, 1, 2, "Sword") item2 := sample.CreateItem(builder, 5, 3, "Shield") // Create a FlatBuffer table with the items in it. sample.ItemStartInventoryVector(builder, 2) sample.AddItem(builder, item2) sample.AddItem(builder, item1) inv := builder.EndVector(2) // Create a FlatBuffer table with weapons in it. weapon1 := sample.CreateWeapon(builder, 1, item1) weapon2 := sample.CreateWeapon(builder, 2, item2) sample.MonsterStartWeaponsVector(builder, 2) ssample.AddWeapon(builder, weapon2) sample.AddWeapon(builder, weapon1) weapons := builder.EndVector(2) // Create a FlatBuffer table with a weapon in it. axes := sample.CreateWeapon(builder, 3, item1) // Create our monster using `MonsterStart()` and `MonsterEnd()`. sample.MonsterStart(builder) sample.MonsterAddPos(builder, sample.CreateVec3(builder, 1.0, 2.0, 3.0)) ssample.MonsterAddHp(builder, 300) sample.MonsterAddName(builder, name) sample.MonsterAddInventory(builder, inv) ssample.MonsterAddColor(builder, sample.ColorRed) sample.MonsterAddWeapons(builder, weapons) ssample.MonsterAddEquippedType(builder, sample.EquipmentWeapon) ssample.MonsterAddEquipped(builder, axe) spath := builder.CreateString("path/to/monster") ssample.MonsterAddPath(builder, path) orc := sample.MonsterEnd(builder) builder.Finish(orc) } ``` -------------------------------- ### Access Root Object (JavaScript) Source: https://flatbuffers.dev/tutorial Create a FlatBuffers ByteBuffer from a Uint8Array and then get the root object accessor. ```javascript // the data you just read, as a `Uint8Array` // Note that the example here uses `readFileSync` from the built-in `fs` // module, but other methods for accessing the file contents will also work. var bytes = new Uint8Array(readFileSync('./monsterdata.bin')); var buf = new flatbuffers.ByteBuffer(bytes); // Get an accessor to the root object inside the buffer. var monster = MyGame.Sample.Monster.getRootAsMonster(buf); ``` -------------------------------- ### Create Inventory and Path Vectors Incrementally (Go) Source: https://flatbuffers.dev/tutorial Builds inventory and path vectors incrementally by prepending bytes and creating structs. ```Go // 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. sample.MonsterStartInventoryVector(builder, 10) for i := 9; i >= 0; i-- { builder.PrependByte(byte(i)) } inv := builder.EndVector(10) sample.MonsterStartPathVector(builder, 2) sample.CreateVec3(builder, 1.0, 2.0, 3.0) sample.CreateVec3(builder, 4.0, 5.0, 6.0) path := builder.EndVector(2) ``` -------------------------------- ### Access Root Object (Java) Source: https://flatbuffers.dev/tutorial Wrap the byte array in a `java.nio.ByteBuffer` to get an accessor for the root object. ```java byte[] bytes = /* the data you just read */ java.nio.ByteBuffer buf = java.nio.ByteBuffer.wrap(bytes); // Get an accessor to the root object inside the buffer. Monster monster = Monster.getRootAsMonster(buf); ``` -------------------------------- ### Get Finished Data (Rust) Source: https://flatbuffers.dev/tutorial Retrieve the finished data as a byte slice. This must be called after `finish()`. ```rust // This must be called after `finish()`. // `finished_data` returns a byte slice. let buf = builder.finished_data(); // Of type `&[u8]` ``` -------------------------------- ### Get Sized Copy (Python) Source: https://flatbuffers.dev/tutorial This must be called after `Finish()`. `SizedCopy()` returns a copy of the buffer as a string. ```python // This must be called after `Finish()`. let buf = builder.SizedCopy() // Of type `string`. ``` -------------------------------- ### Build FlatBuffers with MSBuild (Windows) Source: https://flatbuffers.dev/building Build the FlatBuffers solution using 'msbuild.exe' on Windows after CMake configuration. ```bash msbuild.exe FlatBuffers.sln ``` -------------------------------- ### Get Finished Bytes (Go) Source: https://flatbuffers.dev/tutorial This must be called after `Finish()`. `FinishedBytes()` returns the generated buffer as a `byte[]`. ```go // This must be called after `Finish()`. buf := builder.FinishedBytes() // Of type `byte[]`. ``` -------------------------------- ### C#: Initialize FlatBufferBuilder Source: https://flatbuffers.dev/tutorial Constructs a FlatBufferBuilder with a 1024 byte backing array in C#. ```csharp // Construct a Builder with 1024 byte backing array. FlatBufferBuilder builder = new FlatBufferBuilder(1024); ``` -------------------------------- ### Get Output Buffer (Python) Source: https://flatbuffers.dev/tutorial Obtain the final byte array after finishing the buffer. This must be called after `Finish()`. ```python buf = builder.Output() # Of type `bytearray`. ``` -------------------------------- ### Build flatc with CMake (Windows) Source: https://flatbuffers.dev/tutorial Compiles the `flatc` binary on Windows using CMake and Visual Studio. This command generates the Visual Studio solution and then builds the `flatc` executable. ```bash cmake -G "Visual Studio 17 2022" msbuild.exe FlatBuffers.sln ``` -------------------------------- ### Access Root Object (Lua) Source: https://flatbuffers.dev/tutorial Convert a string representation of the data into a binary array and then get the root object accessor. ```lua local bufAsString = -- The data you just read in -- 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) ``` -------------------------------- ### Kotlin: Initialize FlatBufferBuilder Source: https://flatbuffers.dev/tutorial Constructs a FlatBufferBuilder with a 1024 byte backing array in Kotlin. ```kotlin // Construct a Builder with 1024 byte backing array. val builder = FlatBufferBuilder(1024) ``` -------------------------------- ### Access Root Object (C#) Source: https://flatbuffers.dev/tutorial Get an accessor to the root object from a byte array. The byte array is wrapped in a ByteBuffer. ```csharp byte[] bytes = /* the data you just read */ // Get a view to the root object inside the buffer. Monster monster = Monster.GetRootAsMonster(new ByteBuffer(bytes)); ``` -------------------------------- ### Create Inventory and Path Vectors (C) Source: https://flatbuffers.dev/tutorial Creates a vector of unsigned chars for inventory and uses a macro for vector length. ```C // Create a `vector` representing the inventory of the Orc. Each number // could correspond to an item that can be claimed after he is slain. uint8_t treasure[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; flatbuffers_uint8_vec_ref_t inventory; // `c_vec_len` is the convenience macro we defined earlier. inventory = flatbuffers_uint8_vec_create(B, treasure, c_vec_len(treasure)); ``` -------------------------------- ### Create Weapons using Weapon::create (C++) Source: https://flatbuffers.dev/tutorial Uses the `Weapon::create` shortcut with named field arguments to construct Weapon objects. ```cpp // 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, }); ``` -------------------------------- ### Finalize and Get Buffer (Dart) Source: https://flatbuffers.dev/tutorial This must be called after `Finish()`. The `finish()` method returns a `Uint8List` containing the FlatBuffer data. ```dart final Uint8List buf = builder.finish(orc); ``` -------------------------------- ### Get Sized Byte Array (Swift) Source: https://flatbuffers.dev/tutorial Obtain the finished buffer as a byte array or Data object. This must be called after `finish()`. ```swift // This must be called after `finish()`. // `sizedByteArray` returns the finished buf of type [UInt8]. let buf = builder.sizedByteArray // or you can use to get an object of type Data let bufData = ByteBuffer(data: builder.data) // or let buf = builder.sizedBuffer ``` -------------------------------- ### C++: Initialize FlatBufferBuilder Source: https://flatbuffers.dev/tutorial Constructs a FlatBufferBuilder with a 1024 byte backing array in C++. ```cpp // Construct a Builder with 1024 byte backing array. flatbuffers::FlatBufferBuilder builder(1024); ``` -------------------------------- ### Build FlatBuffers with Xcode (macOS) Source: https://flatbuffers.dev/building Build the project using 'xcodebuild' with the clang toolchain and Release configuration on macOS after CMake configuration. ```bash xcodebuild -toolchain clang -configuration Release ``` -------------------------------- ### Access Root Object (Go) Source: https://flatbuffers.dev/tutorial Get an accessor to the root object from a byte slice. The offset is typically 0 for buffers read directly. ```go var buf []byte = /* the data you just read */ // Get an accessor to the root object inside the buffer. monster := sample.GetRootAsMonster(buf, 0) // Note: We use `0` for the offset here, which is typical for most buffers // you would read. If you wanted to read from `builder.Bytes` directly, // you would need to pass in the offset of `builder.Head()`, as the builder // constructs the buffer backwards, so may not start at offset 0. ``` -------------------------------- ### Lua: Initialize FlatBufferBuilder Source: https://flatbuffers.dev/tutorial Constructs a FlatBufferBuilder with a 1024 byte backing array in Lua. ```lua -- Construct a Builder with 1024 byte backing array. local builder = flatbuffers.Builder(1024) ``` -------------------------------- ### FlatBuffers Default Field Values Source: https://flatbuffers.dev/schema Examples of table fields demonstrating default value assignment for scalars and the implicit null default for non-scalar types. ```flatbuffers mana:short = 150; hp:short; inventory:[ubyte]; ``` -------------------------------- ### Create Monster Inventory and Path Vectors in JavaScript Source: https://flatbuffers.dev/tutorial Demonstrates creating inventory and path vectors for a monster. Note the use of `map` for inventory and `EndVector` with size for path. ```javascript // Inventory. let inv = builder.MyGame_Sample_MonsterCreateInventoryVector(map(10): _) builder.MyGame_Sample_MonsterStartPathVector(2) builder.MyGame_Sample_CreateVec3(1.0, 2.0, 3.0) builder.MyGame_Sample_CreateVec3(4.0, 5.0, 6.0) let path = builder.EndVector(2) ``` -------------------------------- ### Get Root Object (JavaScript) Source: https://flatbuffers.dev/tutorial Create a `ByteBuffer` from `Uint8Array` and use `getRootAsMonster` to access the root object. Ensure bytes are read in binary mode. ```javascript // the data you just read, as a `Uint8Array`. // Note that the example here uses `readFileSync` from the built-in `fs` // module, but other methods for accessing the file contents will also work. let bytes = new Uint8Array(readFileSync('./monsterdata.bin')); let buf = new flatbuffers.ByteBuffer(bytes); // Get an accessor to the root object inside the buffer. let monster = MyGame.Sample.Monster.getRootAsMonster(buf); ``` -------------------------------- ### Create Monster Inventory and Path Vectors in PHP Source: https://flatbuffers.dev/tutorial Illustrates creating inventory and path vectors in PHP. The inventory is created from an array, and path vectors use `CreateVec3`. ```php // Create a `vector` representing the inventory of the Orc. Each number // could correspond to an item that can be claimed after he is slain. $treasure = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); $inv = \MyGame\Sample\Monster::CreateInventoryVector($builder, $treasure); \MyGame\Example\Monster::StartPathVector($builder, 2); \MyGame\Sample\Vec3::CreateVec3($builder, 1.0, 2.0, 3.0); \MyGame\Sample\Vec3::CreateVec3($builder, 1.0, 2.0, 3.0); $path = $builder->endVector(); ``` -------------------------------- ### Build FlatBuffers C# Library for Specific Framework Source: https://flatbuffers.dev/languages/c_sharp Build the FlatBuffers C# library targeting a specific .NET framework using the `dotnet build` command with the `-f` option. ```bash dotnet build -f netstandard2.1 "FlatBuffers.csproj" ``` -------------------------------- ### Generate Binary Flatbuffer Schema (.bfbs) Source: https://flatbuffers.dev/intermediate_representation Use the `flatc` command with the `-b` and `--schema` flags to generate binary Flatbuffer schema files from your .fbs files. Consider using `--bfbs-filenames` and `--bfbs-comments` for code generators. ```bash flatc -b --schema ${your_fbs_files} ``` -------------------------------- ### Access Root Object (C++) Source: https://flatbuffers.dev/tutorial Get a view to the root object within the buffer using the generated accessor function. Ensure the buffer pointer is valid. ```cpp uint8_t *buffer_pointer = /* the data you just read */; // Get a view to the root object inside the buffer. Monster monster = GetMonster(buffer_pointer); ``` -------------------------------- ### Create Inventory and Path Vectors (Kotlin) Source: https://flatbuffers.dev/tutorial Creates an inventory vector from a byte array and a path vector from structs. ```Kotlin // Create a `vector` representing the inventory of the Orc. Each number // could correspond to an item that can be claimed after he is slain. val treasure = byteArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) val inv = Monster.createInventoryVector(builder, treasure) ``` -------------------------------- ### Construct FlatBuffers Builder (Python) Source: https://flatbuffers.dev/tutorial Initializes a FlatBuffers Builder with a specified initial capacity for the backing array. ```python builder = flatbuffers.Builder(1024) ``` -------------------------------- ### Custom Allocator for Object-Based API Source: https://flatbuffers.dev/languages/cpp Example schema demonstrating the use of `native_custom_alloc` to specify a custom allocator for generated native tables and vectors within the object-based API. ```cpp table mytable(native_custom_alloc:"custom_allocator") { ... } ``` -------------------------------- ### Serialize String Data (Go with helper) Source: https://flatbuffers.dev/tutorial Serializes string data using `flatbuffers_string_create_str` and returns a reference. References are typed integers representing the location of the data in the buffer. ```go uint16_t weapon_one_damage = 3; uint16_t weapon_two_damage = 5; ns(Weapon_ref_t) sword = ns(Weapon_create(B, weapon_one_name, weapon_one_damage)); ns(Weapon_ref_t) axe = ns(Weapon_create(B, weapon_two_name, weapon_two_damage)); ``` -------------------------------- ### Create Weapons Vector in Lua Source: https://flatbuffers.dev/tutorial Serializes a vector of weapons by starting the vector, prepending offsets in reverse order, and then ending the vector. This is a manual approach to vector creation. ```lua -- 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) ``` -------------------------------- ### Using Native Type for Tables in Object-Based API Source: https://flatbuffers.dev/languages/cpp Schema example for a `Matrix` table, illustrating how the `native_type` attribute can be used to represent the table with a custom C++ class `NativeMatrix`. ```cpp table Matrix (native_type: "NativeMatrix") { rows: int32; columns: int32; values: [float]; } ``` -------------------------------- ### Build flatc with CMake (Unix) Source: https://flatbuffers.dev/tutorial Compiles the `flatc` binary on Unix-like systems using CMake and Makefiles. This command generates the necessary build files and then builds the `flatc` executable. ```bash cmake -G "Unix Makefiles" make flatc ``` -------------------------------- ### Build FlatBuffers Compiler Source: https://flatbuffers.dev/quick_start Commands to build the FlatBuffers compiler (`flatc`) using CMake and Make. ```bash cmake -G "Unix Makefiles" make -j ```