Compare commits

...

129 Commits

Author SHA1 Message Date
Derek Bailey
1c514626e8 FlatBuffers Version 25.2.10 2025-02-10 20:25:03 -08:00
Derek Bailey
820a7f277f Remove old documentation 2025-02-10 20:13:39 -08:00
Marcel
396c3f56df Upgrade dependencies (#8516)
As rules_swift bumped the compatibility level, this is required if any dependent repo wants to use the newer version.
2025-02-05 09:01:46 -08:00
mustiikhalil
c49e81d6ec Adds swift 6 to the build matrix (#8414)
Bump min version of swift to be 5.9
2025-02-04 09:11:46 -08:00
Marcin Radomski
a285e7ef1a Rust reflection: simplify dependencies, fix Android build compatibility (#8512)
* flatbuffers Rust reflection: replace num with num-traits

num crate is a wrapper over num-traits and a few other crates, that
reexports the APIs from all of them. We only need num-traits.

Signed-off-by: Marcin Radomski <dextero@google.com>

* Rust reflection: drop dependency on stdint crate

We only use it to get intmax_t for deriving alignment, which is an alias
for `core::ffi::c_long` [1]. We can use that directly instead.

[1] https://docs.rs/stdint/1.0.0/stdint/type.intmax_t.html

Signed-off-by: Marcin Radomski <dextero@google.com>

* Rust reflection: drop dependency on escape_string crate

It's used to format a string used for debugging only, so we might as
well use the builtin Debug representation of a string.

Signed-off-by: Marcin Radomski <dextero@google.com>

* Rust codegen: add derives on generated bitflags

Otherwise it limits the use of structs generated for reflection.fbs
in Rust reflection API.

Signed-off-by: Marcin Radomski <dextero@google.com>

* Rust flatbuffers: update bitflags dependency to 2.8

Signed-off-by: Marcin Radomski <dextero@google.com>

* Rust codegen: use bitflags v2 API for converting from bits

from_bits_unchecked was replaced with safe from_bits_retain.

Signed-off-by: Marcin Radomski <dextero@google.com>

* Regenerate Rust code after idl change

Signed-off-by: Marcin Radomski <dextero@google.com>

* Regenerate reflection_generated.rs

With flatc --rust ../../../reflection/reflection.fbs

Signed-off-by: Marcin Radomski <dextero@google.com>

* ts/BUILD.bazel: add missing import

Found by Buildifire presubmit:

  Function "sh_binary" is not global anymore and needs to be loaded from
  "@rules_shell//shell:sh_binary.bzl".

Signed-off-by: Marcin Radomski <dextero@google.com>

* Update expected value in generated_code_debug_prints_correctly test

In bitflags v2, the debug string representation of enum values is
different than it was in v1:
  Blue -> Color(Blue)
  (empty) -> LongEnum(0x0)

This change adjusts the expected test value.

Signed-off-by: Marcin Radomski <dextero@google.com>

* Fix tests build on Swift 5.8

grpc-swift 1.4.1 depends on swift-nio-ssl 2.14.0+ [1]. swift-nio-ssl 2.29.1
published on 2025-01-30, introduced some code [2] that uses a "switch
expression syntax" supported since Swift 5.9 [3]. Attempts to compile it with
Swift 5.8 cause build errors.

swift-nio-ssl project doesn't seem to support Swift 5.8. A commit from
2024-10-29 removes a "deprecated reference to a Swift 5.8 pipeline" [4].

swift-nio-ssl 2.29.0 is the last version that can be compiled with Swift
5.8. This commit pins it to that exact version.

[1] 66e27d7e84/Package.swift (L33)
[2] 3cb4d5ad12 (diff-bc1db1321ff689c2819245dcce1a3080554f0fc13f81b8d326c97e7d42717c8fR54)
[3] https://github.com/swiftlang/swift-evolution/blob/main/proposals/0380-if-switch-expressions.md
[4] 8a6b89d9a4

---------

Signed-off-by: Marcin Radomski <dextero@google.com>
Co-authored-by: Marcin Radomski <dextero@google.com>
2025-02-04 08:40:31 -08:00
Derek Bailey
0312061985 FlatBuffers Version 25.1.24 2025-01-24 16:36:11 -08:00
Taiju Tsuiki
9f94ceedbc [C++] Avoid adding semicolon after a statement (#8488)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2025-01-24 11:00:18 -08:00
Marcel
bcd2b9d039 Add Bazel docs (#8510) 2025-01-24 10:57:52 -08:00
Marcel
82fefbf252 Remove Bazel WORKSPACE setup. (#8509) 2025-01-24 18:16:10 +00:00
Sebastian Barfurth
65e49faf76 Bump the versions of all aspect Bazel dependencies (#8508)
* bump all aspect dependency versions to latest

* add workspace file to test bazel repo
2025-01-24 10:09:22 -08:00
Marcel
50be3cfe8c Test external modules explicitly in CI (#8507)
This setup is much simpler than calling Bazel from within Bazel
and making sure files and flags are set up correctly.

Co-authored-by: Derek Bailey <derekbailey@google.com>
2025-01-23 23:04:06 +00:00
Marcel
026c243dc5 Add support for Bazel 7 and 8 in Bazel CI (#8505)
* Add missing file to filegroup for bazel integration tests

Fixup after a9257b6963.

* Align versions in bazel_respository_test_dir with root

* Update XCode version to 15.2

This is the oldest available version.

* Add WORKSPACE.bzlmod

* Add support for Bazel 7

* Add support for Bazel 8 in CI
2025-01-23 14:59:14 -08:00
Marcel
a9257b6963 Fix npm bzlmod (#8506)
* Restrict visibility of exported file

* Align npm_translate_lock attrs

* Remove defs_bzl_filename attr

* Align root_package with pnpm-lock.yaml location

Use a symlink to avoid copying the file.
2025-01-23 21:01:31 +00:00
Marcel
fceafd438d Improve Bazel CI (#8502)
* Update Buildkite Bazel CI

Restructure presubmit.yml to support matrix.

* Remove testing Ubuntu 18.04

The available LLVM 6.0 is too old to support std::filesystem.

* Add testing in Ubuntu 22.04

* Use Bazel version 6.5.0 in integration test
2025-01-23 12:10:27 -08:00
Marcel
33a15d63cf Fix reflection.fbs import path (#8499)
We need to copy the .fbs files into the package used for .bfbs files.
This is necessary as flatc doesn't provide support to specify the full
output file name for an .fbs file in a different folder.
I tried OUTPUT_FILE env var but this doesn't seem to be honored by
flatc.
2025-01-23 19:43:23 +00:00
Marcel
ad6d6638f3 Fix Bzlmod (#8503)
* Fix Bzlmod npm repo name

* Fix Bazel integration tests with Bzlmod
2025-01-23 08:52:48 -08:00
Derek Bailey
69ac6a712d Add bazel ci (#8497) 2025-01-22 13:41:45 -08:00
Marcel
4b69b27d43 Also use rules_bazel_bazel_integration_test dependency with Bzlmod (#8498)
* Also use rules_bazel_bazel_integration_test dependency with Bzlmod

* Update versions
2025-01-22 08:22:53 -08:00
Derek Bailey
9318c6c981 Update Evolution doc 2025-01-21 21:28:32 -08:00
Derek Bailey
df287ee6a7 FlatBuffers Version 25.1.21 2025-01-21 17:22:30 -08:00
Marcel
0d7bf7e8a7 Add support for Bzlmod (#8494) 2025-01-21 16:53:46 -08:00
Marcel
e67310bf1c Use rules_bazel_integration_test to download Bazel binary (#8495) 2025-01-21 16:51:08 -08:00
Marcel
121c4c99ae Use Label() to resolve repo name (#8493)
This makes sure it doesn't break users when they choose a different repo_name.
2025-01-21 16:49:57 -08:00
Marcel
27f5a0fdae Add missing headers to runtime_cc target (#8492)
Transitive headers like array.h have not been available in the runtime_cc target causing the build to fail. Adding all public headers to make sure transitive headers of flatbuffers.h are available.
2025-01-21 08:06:12 -08:00
Ben Beasley
3592b19150 Fix a minor typo in flatc --help output (#8468) 2025-01-16 07:10:25 +00:00
Chan Wang
733e432bfd Rust full reflection (#8102)
* #Rust Create a crate for reflection

* #Rust Add a crate for reflection tests and helper to access schema

* #Rust Get root table of a buffer and access field with schema

* #Rust Add 'Struct' struct and corresponding getter

* #Rust Add functions of getting any table/struct field value as integer/float/string

* #Rust Add setters for scalar fields

* #Rust Add setter for string fields

* #Rust Add getter for Table/Vector fields

* #Rust Add buffer verification

* Add a 'SafeBuffer' struct which provides safe methods for reflection

It verifies buffer against schema during construction and provides all the unsafe getters in lib.rs in a safe way

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
2025-01-15 10:03:10 -08:00
Derek Bailey
5414e04b45 Add imports for bazel (#8486) 2025-01-15 09:24:34 -08:00
Derek Bailey
c9a286bf29 Update mkdocs.yml redirect
Fixes #8485
2025-01-15 08:21:09 -08:00
Derek Bailey
f9a70c79f1 Update release.yml for Maven 2025-01-13 22:35:04 -08:00
Derek Bailey
1eb4bd3ca7 cleanup github ci 2025-01-13 22:07:54 -08:00
Derek Bailey
41e47e4951 update copyright date 2025-01-13 21:45:22 -08:00
Derek Bailey
4999936289 add 404 info 2025-01-13 21:31:41 -08:00
Derek Bailey
8e2852fa73 Update issue templates 2025-01-13 21:28:41 -08:00
Derek Bailey
7e52f59f14 finish porting over languages in tutorial 2025-01-13 21:11:50 -08:00
Derek Bailey
1ff248739e format the tutorial for all the languages 2025-01-11 10:43:50 -08:00
Derek Bailey
2cffba28b4 Start to support all languages in tutorial 2025-01-10 15:15:40 -08:00
Derek Bailey
34f0728ea2 fix c++ style in embedded content 2025-01-10 12:57:24 -08:00
Derek Bailey
569e6cb461 Fixed broken links 2025-01-10 12:55:35 -08:00
Bhargava Srinarasi
086097ff94 A couple of small updates to the docs (#8477)
* Mention uint8 as an alias to ubyte

as it's referenced in the note below

* Remove an unfinished sentence.
2025-01-10 19:02:09 +00:00
Derek Bailey
2b0ce37b12 Quick copy of all pages 2025-01-09 23:36:46 -08:00
Derek Bailey
67bf1084c0 Update docs.yml to install mkdocs-redirects 2025-01-09 22:13:28 -08:00
Shynur
f82c4ac904 fix typo in tutorial (#8476) 2025-01-10 05:53:27 +00:00
Derek Bailey
9a40ab2495 Remove Resource path 2025-01-09 21:30:01 -08:00
Derek Bailey
5c14ee7e8b Update copy location 2025-01-09 21:27:04 -08:00
Derek Bailey
26e77dce41 Update copy location 2025-01-09 21:25:03 -08:00
Derek Bailey
6913c34e62 Update data location in tests 2025-01-09 21:20:27 -08:00
Derek Bailey
0222cd4a63 Missing .exe 2025-01-09 20:59:30 -08:00
Derek Bailey
0042afa5e2 Update output location with net6.0 and net8.0 2025-01-09 20:52:58 -08:00
Derek Bailey
8852f10a84 Update output location 2025-01-09 20:41:40 -08:00
Derek Bailey
a8df3c8f35 Remove outpath altogether 2025-01-09 20:32:43 -08:00
Derek Bailey
b8629d402e Use OutputPath instead of PublishDir 2025-01-09 20:22:13 -08:00
Derek Bailey
ccdab58c11 Go to setup-donet@v4.2.0 2025-01-09 20:16:36 -08:00
Derek Bailey
a96fe8f206 Fix warnings on Build .NET Windows 2025-01-09 20:13:24 -08:00
Fergus Henderson
99fda81905 Fix crash for TypeScript enum in substruct (#8430)
See https://github.com/google/flatbuffers/issues/8299.
2025-01-08 01:38:34 +00:00
Derek Bailey
8694806f14 schema.md Fixed some warnings (#8472) 2024-12-27 12:29:22 -08:00
Derek Bailey
5a75ad407d mkdocs.yml add footer and other info (#8471) 2024-12-27 11:47:49 -08:00
Derek Bailey
2d86857bec Add Annotating Docs (#8470)
* `quick_start.md`: Add quick start guide

* `annotation.md`: Add section on annotating flatbuffers
2024-12-27 11:25:21 -08:00
Derek Bailey
0f90dc8290 quick_start.md: Add quick start guide (#8469) 2024-12-27 08:52:22 -08:00
Derek Bailey
c9125e6385 flatc.md Add more documentation (#8467)
* CNAME: add custom domain

* `flatc.md`: Add more documentation
2024-12-24 12:15:14 -08:00
mustiikhalil
28ddfaeda7 Fixes a bug that made a copy of the changing vars within the verifier leading to an incorrect count (#8451)
Removes all the unneeded keyword (mutating) from verifier

Adds tests to verify depth
2024-12-23 22:29:09 -08:00
Derek Bailey
7e59e0727c CNAME: add custom domain (#8465) 2024-12-23 22:22:24 -08:00
Derek Bailey
79d9e33ea3 Update docs.yml
replace `main` with `master` that we are still using
2024-12-23 22:07:28 -08:00
Derek Bailey
bbb6b932fc contributions.md Add doc about how to contribute to flatbuffers (#8464) 2024-12-23 22:06:04 -08:00
Derek Bailey
46cc3d6432 docs.yml enable for pushes to main branch (#8463) 2024-12-23 20:49:27 -08:00
Derek Bailey
fb3ccd36c0 docs.yml Add workflow for updating docs (#8462) 2024-12-23 16:04:15 -08:00
Derek Bailey
492475a1b2 Add new Docs source files (#8461) 2024-12-23 15:55:56 -08:00
Derek Bailey
c75a0154eb Move docs/ to docs-old/ 2024-12-23 15:32:19 -08:00
Derek Bailey
a2cd1ea3b6 FlatBuffers Version 24.12.23 (#8459)
* FlatBuffers Release 24.12.23

* Fixed missing generated file version checks

* Run generate_code and fix cpp17 tests
2024-12-23 12:55:07 -08:00
Derek Bailey
32e63af684 Kotlin MacOs switch to macos-13
Switch off of macos-latest which no longer has the 14.3 xcode installed. Version macos-13 does.

We should probably update our kotlin though.
2024-12-23 09:10:46 -08:00
mustiikhalil
1f4a9038ce [Swift] Improves vectors performance & arrays within lib (#8415)
* Improves vectors performance and adds a benchmark to vectors of offsets in swift

Improves performance for all arrays and for loops

Uses a tuple instead of allocating a struct each time we start iterating over fieldloc

Updates benchmark library

* Fixing swift Wasm ci
2024-11-19 07:02:47 +01:00
Ivan Dlugos
a9df44828d dart: use enhanced enums (#8313)
* dart: rename enums.fbs

* feat: use dart enhanced enums

* generate code

---------

Co-authored-by: Wouter van Oortmerssen <aardappel@gmail.com>
2024-11-18 17:31:19 +00:00
Cameron Mulhern
5f453ef738 Removes 'size' and 'alignment' as Rust keywords (#8139)
* Adds fields for possibly reserved words to rust_namer_test

* Removes size and alignment as rust reserved words
2024-11-12 05:13:02 +00:00
Benjamin Kietzman
49061f8c7c use ALIGN for Push::alignment in struct types (#8398)
* use ALIGN for Push::alignment in struct types

* regenerate and add a test for struct alignment
2024-10-28 08:42:55 -07:00
Wouter van Oortmerssen
807adb73b2 FlexBuffers: support "natural utf8" output in ToString (#8426) 2024-10-12 14:34:06 -07:00
Mikhail
2f59a0319b Update grpc-core version (#8412)
* Update grpc-core version

io.grpc:grpc-core package in version 1.36.0 contains multiple [CVE's](https://mvnrepository.com/artifact/io.grpc/grpc-core/1.36.0).
Bump grpc-core version to latest 1.68.0 version to mitigate potential vulnerabilities.

* Update grpc version to 1.67.1

grpc was mistakenly released to maven under version 1.68.0 whenever a real release was done for version 1.67.1 [1]. The mistake was fixed later.

[1] https://github.com/grpc/grpc-java/releases
2024-10-05 18:24:05 -07:00
mustiikhalil
6a8898573c [Swift] Updates CocoaPods author info & fixes bug with versioning not working as expected (#8328)
* Fix versioning not being able to parse vX.Y.Z and updates author

* Adds BUILD_LIBRARY_FOR_DISTRIBUTION flag for cocoapods
2024-10-05 00:17:05 +02:00
mustiikhalil
d7a70db6ac (fix): #8408 fixes a bug where the capacity of the buffer isnt verified before trying to verify the ID (#8413) 2024-10-05 00:16:41 +02:00
mustiikhalil
b127c57ff0 Fixes spelling mistake in the word position (#8330) 2024-10-05 00:16:28 +02:00
Wouter van Oortmerssen
2436bd8175 Attempt to fix Rust CI (#8411)
by undoing what appears to have broken it: https://github.com/google/flatbuffers/pull/8372
2024-09-30 09:39:38 -07:00
Wouter van Oortmerssen
69a53e495d Use actions/upload-artifact@v4 on CI (#8410) 2024-09-27 15:39:44 -07:00
Ikko Eltociear Ashimine
c7a8102b12 docs: update README.md (#8383)
compliation -> compilation
2024-09-05 18:50:35 -07:00
Mikhail
2146bacd2e Update libs.versions.toml (#8387)
Fix CVE-2022-25647

The package com.google.code.gson:gson before 2.8.9 is vulnerable to Deserialization of Untrusted Data via the writeReplace() method in internal classes, which may lead to denial of service attacks.

Bump up version of the gson package.

https://github.com/advisories/GHSA-4jrv-ppp4-jm57
2024-09-06 01:26:51 +00:00
nolen777
8db59321d9 Add a unit test for odd-sized small structs (for #8117) (#8363)
* add an odd sized test

* formatting

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
2024-08-20 00:27:32 -04:00
pkasting
42879f6ea6 [jumbo] Add begin()/end() to DetachedBuffer. (#8370)
This allows this type to meet the requirements of e.g.
std::ranges::range, which is necessary for it to work with the
std::span range constructor, or the "non-legacy" constructor for
Chromium's base::span.

Bug: none

Co-authored-by: Derek Bailey <derekbailey@google.com>
2024-08-20 04:12:35 +00:00
Gunnar Schulze
7833affd7e Upgrade Rust dependencies (#8372)
* [Rust] Upgrade bitflags to version 2.6.0

* [Rust] Upgrade num_enum to version 0.7.3

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
2024-08-20 04:04:09 +00:00
LamTrinh.Dev
c065e972db Remove unused comment and fix typo. (#8366)
* Update NativeObject.swift

Correct the word.

* Update ByteBuffer.swift

Type parameter does not existing, remove it.

* Update ByteBuffer.swift

Correct the word.
2024-08-19 23:22:00 -04:00
alphalex-google
06b12d55ea Add "empty()" to vector (#8369)
This is just another `std`-ism that is being added.

Co-authored-by: Derek Bailey <derekbailey@google.com>
2024-08-19 20:22:30 -04:00
Marcin Lewandowski
baddf90599 Add parentheses in FLATBUFFERS_MAX_BUFFER_SIZE, FLATBUFFERS_MAX_64_BUFFER_SIZE to avoid preprocessor definition collision (#8377)
In case when flatbuffers are being used along with other project that defines "max" preprocessor macro, the ::max() in FLATBUFFERS_MAX_BUFFER_SIZE and FLATBUFFERS_MAX_64_BUFFER_SIZE is incorrectly being expanded to the macro. Adding parentheses enforces function-like interpretation.

Co-authored-by: Derek Bailey <derekbailey@google.com>
2024-08-19 19:51:15 -04:00
Derek Bailey
8b35a6bc32 Bazel: Just target flatc and flatbuffers_test for presubmit 2024-08-19 16:42:51 -07:00
Derek Bailey
6cb4d671a8 Fixes LICENSE file in python
Fixes: #8376
2024-08-19 16:09:27 -07:00
Anton Bobukh
fb9afbafc7 [gRPC] Update the code generator for Python to produce typed handlers (#8326)
* Move `namer.h` and `idl_namer.h` to `include/codegen` so they can be reused from `grpc` dirqectory.

* [gRPC] Update the Python generator to produce typed handlers and Python stubs if requested.

* [gRPC] Document the newly added compiler flags.
2024-06-18 16:02:57 -07:00
Felix
dafd2f1f29 [Python] Render enums as Python IntEnum (#8145)
This allows enums to be type check with mypy.
They will still behave like ints ->
> IntEnum is the same as Enum,
> but its members are also integers and can be used anywhere
> that an integer can be used.
> If any integer operation is performed with an IntEnum member,
> the resulting value loses its enumeration status.
https://docs.python.org/3/library/enum.html#enum.IntEnum

Only if the --python-typing flag is set.
2024-06-03 08:39:14 -07:00
Anton Bobukh
6ede1ccc9e [BinaryAnnotator] Add more options that control the generation of .afb files (#8323)
* [BinaryAnnotator] Add more options that control the generation of `.afb` files.

* [BinaryAnnotator] Update the include paths.
2024-05-29 13:34:38 -07:00
Anton Bobukh
8755c35a18 [C++] Update the validator to skip structs in namespaces other than the current one. (#8324)
* [Python] Generate `.pyi` stub files when `--python-typing` is on.

To support this change, the following modifications were made:

-  added a new option to disable `numpy` helpers generation;
-  added a new flag to control the target Python version:

   `--python-version` can be one of the following:

   - `0.x.x` – compatible with any Python version;
   - `2.x.x` – compatible with Python 2;
   - `3.x.x` – compatible with Python 3.
-  added codegen utilities for Python;
-  added a note that the generated .py file is empty.

* [C++] Update the validator to skip structs in namespaces other than the current one.
2024-05-29 13:16:37 -07:00
mustiikhalil
75f05d6389 Sets Swift minimum version to 5.8 (#8228)
Updates copyright from 2023 to 2024 & formats code - updates formatting rules

Updates CI to run with swift 5.8

Adds wasmer & updates command to run carton as a swift plugin

Update bazelci to also accept swift 5.8

Adds swift 5.10 to the test matrix
2024-05-29 13:07:54 -07:00
Anton Bobukh
3b27f5396e [Python] Generate .pyi stub files when --python-typing is on. (#8312)
* [Python] Generate `.pyi` stub files when `--python-typing` is on.

To support this change, the following modifications were made:

-  added a new option to disable `numpy` helpers generation;
-  added a new flag to control the target Python version:

   `--python-version` can be one of the following:

   - `0.x.x` – compatible with any Python version;
   - `2.x.x` – compatible with Python 2;
   - `3.x.x` – compatible with Python 3.
-  added codegen utilities for Python;
-  added a note that the generated .py file is empty.

* [Python] Update Bazel build rules.

* [Python] Update Bazel build rules.

* [Python] Run buildifier on BUILD.bazel files.

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
2024-05-29 12:47:29 -07:00
Dominik Lohmann
58c8eb5847 [C++] Allow using FLATBUFFERS_MIN_BUFFER_SIZE in other namespaces (#8229)
This is a small change that makes `FLATBUFFERS_MIN_BUFFER_SIZE` usable
outside of the `flatbuffers` namespace.
2024-05-29 03:59:03 +00:00
Felix
0e034ecdba [C++] Make code compile with -Wfloat-equal (#8221)
This will allow the code to be compiled with `-Wfloat-equal`
as this would result in the folowing warning/error:
vendor/flatbuffers/include/flatbuffers/base.h:465:69:
  error: comparing floating point with == or != is unsafe [-Werror,-Wfloat-equal]
template<typename T> inline bool IsTheSameAs(T e, T def) { return e == def; }

But the way it is used in flatbuffers it is ok to compare floating
points with ==.

Co-authored-by: Derek Bailey <derekbailey@google.com>
2024-05-29 02:52:14 +00:00
iS_lANDER
0f8b71180f [FIX] fix the behavior of flatbuffers::Optional to match std::optional when lhs and rhs are both nullopt (#8223)
Co-authored-by: islander <mikudehuane@gmail.com>
Co-authored-by: Derek Bailey <derekbailey@google.com>
2024-05-29 02:40:04 +00:00
Derek Bailey
a5a2da0161 Update release.sh (#8322)
* Update release.sh

Update release script to update rust flexbuffers

* Update Cargo.toml
2024-05-28 18:44:37 -07:00
Derek Bailey
28783927af Update release.yml
Fix pathing in Crates.io publishing.
2024-05-28 18:36:11 -07:00
Derek Bailey
a1378fbd16 Update release.yml
Remove extra -
2024-05-28 18:34:26 -07:00
Derek Bailey
dcacfc5b11 Update release.yml
Use explicit paths in publish-crates. Also adds flexbuffers publishing.
2024-05-28 18:33:04 -07:00
Derek Bailey
f9dabf511a Update release.yml
Update working directory of crates.io publishing
2024-05-28 18:28:18 -07:00
Ricardo Delfin
5ba66f71c5 Added automatic publishing to crates.io on publish (#8263)
* Added automatic publishing to crates.io on publish

* Fixed indentation

* Update release.yml

Change secret name.

* Update release.yml

remove extra space added in merge

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
2024-05-29 01:19:41 +00:00
Tyler Dunn
5adfac9fc3 dart: Fix incorrect write in Float64 write method (#8290)
Co-authored-by: Llamadmiral <Llamadmiral@users.noreply.github.com>
Co-authored-by: Derek Bailey <derekbailey@google.com>
2024-05-29 01:13:10 +00:00
Paulo Pinheiro
c6fce30e9b [Kotlin] Update to kotlin 1.9.10 (#8307)
Update was needed to fix compilation issues on XCode 15.
See more:
https://youtrack.jetbrains.com/issue/KT-60230/Native-unknown-options-iossimulatorversionmin-sdkversion-with-Xcode-15-beta-3

Co-authored-by: Derek Bailey <derekbailey@google.com>
2024-05-28 18:08:01 -07:00
Björn Harrtell
ef30729a71 [.NET] Add netstandard2.0 as target (#8295)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2024-05-28 18:07:43 -07:00
Ben J
30ae5f189c Add more operators. (#8309)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2024-05-29 01:07:34 +00:00
Derek Bailey
299725fe2e Update build.yml (#8321)
Add a scheduled cron job to run all the main tests at 4:45 A.M. to catch dependency regressions.
2024-05-28 18:01:00 -07:00
mustiikhalil
a41fefa1a8 Trying to fix bazel on macOS and Xcode 14.3 (#8304)
* Fixes Bazel issues for windows and ci

Fetching boringssl within the flatbuffers repository, to patch the issues
of not being able to upgrade to Xcode 14.3 due to buildkite throwing
errors. The patch was inspired by the tenserflow patch
https://github.com/tensorflow/tensorflow/issues/60191#issuecomment-1496073147

Removes references of swift from the windows pipeline for bazel

Sets github actions to use xcode 14.3 for kotlin and sets the macOS
build for intel cpus.

* Update build.yml

Remove comment that is not relevant any longer.

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
2024-05-28 17:29:41 -07:00
Derek Bailey
d89f611f6f Update build.yml to ubuntu-24.04 (#8319)
* Update build.yml to ubuntu-24.04

Apparently g++-13 was removed from the ubuntu-22.04 runners.

We also don't have enterprise runners at 24.04 yet, so just use the free ones for now until we get support for those. CI builds might take longer now.

* Update build.yml

Downgrade to g++12 and revert change to using normal runners

* Update build.yml

Go back to ubuntu-24.04 and update both gcc and clang to their latest versions according to [this](https://github.com/actions/runner-images/blob/main/images/ubuntu/Ubuntu2404-Readme.md?plain=1#L16-L20).

* Update build.yml

Go back to g++13 for now, as we get some exotic warning in g++14 for newer C++ standards.

* Update build.yml

Fix the other issues with `macos-latest` going to arm: https://github.com/actions/runner-images/tree/main?tab=readme-ov-file#available-images and that Swift wasn't installed in the ubuntu-24.04 by default.

* Update build.yml

Disable Kotlin MacOs CI
2024-05-28 17:18:00 -07:00
Anton Bobukh
150644d7f4 [gRPC] Add new options to control the gRPC code generation. (#8298)
The new options are:

-  `--grpc-filename-suffix` controls the suffix of the generated files;
-  `--grpc-use-system-headers` controls the type of C++ includes generated;
-  `--grpc-search-path` controls the directory that contains gRPC runtime;
-  `--grpc-additional-header` allows to provide additional dependencies for the generated code.
2024-05-15 08:17:40 -07:00
Anton Bobukh
c696275eaf [Python] Fix various codegen problems (#8292)
* [Python] Fix various codegen problems.

This includes:

-  escaping keywords happens **after** converting the case:
   - currently, `table ClassT` generate `class = Class()` which is invalid Python;
-  imports in `one_file` mode use the filename rather than the type name when resolving module names;
-  use `filename_suffix` instead of the hardcoded `_generated` one;
-  generate empty files if no structs or enums are available. This makes the set of output files more predictable for Bazel.

* [Python] Fix various codegen problems.

This includes:

-  escaping keywords happens **after** converting the case:
   - currently, `table ClassT` generate `class = Class()` which is invalid Python;
-  imports in `one_file` mode use the filename rather than the type name when resolving module names;
-  use `filename_suffix` instead of the hardcoded `_generated` one;
-  generate empty files if no structs or enums are available. This makes the set of output files more predictable for Bazel.
2024-05-01 14:39:47 -07:00
Philipp Schrader
7106d86685 Remove npm/rules_js dependency for C++ only use cases (#7990)
When flatbuffers is being used from a project that has no use for
JavaScript, users encounter an error similar to the following:

    ERROR: Skipping '@com_github_google_flatbuffers//:flatbuffers': error loading package '@com_github_google_flatbuffers//': Unable to find package for @npm//:defs.bzl: The repository '@npm' could not be resolved: Repository '@npm' is not defined.
    WARNING: Target pattern parsing failed.
    ERROR: error loading package '@com_github_google_flatbuffers//': Unable to find package for @npm//:defs.bzl: The repository '@npm' could not be resolved: Repository '@npm' is not defined.
    INFO: Elapsed time: 0.023s
    INFO: 0 processes.
    FAILED: Build did NOT complete successfully (0 packages loaded)
        currently loading: @com_github_google_flatbuffers//

That's not ideal. Users that only care about C++ for example
shouldn't be forced to deal with rules_js and friends.

This patch attempts to fix that by moving the rules_js-specific things
into the `ts` and `tests/ts` directories. This should allow
non-JavaScript projects to ignore rules_js and friends completely.

Here I basically followed the `rules_foo` example from rules_js:
https://github.com/aspect-build/rules_js/tree/main/e2e/rules_foo

The idea is that flatbuffers has its own npm dependencies regardless
of what other projects may have. This means we should not force the
user to import flatbuffers's npm dependencies. The new
`ts/repositories.bzl` file is used by dependents to import
flatbuffers's dependencies. They can still import their own
dependencies. This cleanup allowed me to move all
JavaScript-specific stuff from the top-level directory into
subdirectories.

There should be no changes in this patch in terms of functionality.
It's just a refactor of the rules_js call sites. Users will have to
add a call to the function in `ts/repositories.bzl` in their own
`WORKSPACE` file. They can use
`tests/ts/bazel_repository_test/WORKSPACE` as an example.

Co-authored-by: Derek Bailey <derekbailey@google.com>
2024-04-18 05:06:06 +00:00
Paulo Pinheiro
da6472013f [Kotlin] Add workflow to release kotlin multiplatform version (#8014)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2024-04-17 17:10:39 -07:00
Derek Bailey
e646392647 flatbuffer_builder: Fix GetTemporaryPointer constantness 2024-04-17 16:06:26 +00:00
Michael Beardsworth
e040f4e975 Improve error handling on Object API name collision. (#8275)
If a schema contains a message named e.g. FooT and a message named Foo
while the Object API suffix is T, then two classes with colliding names
will be generated. This scenario will produce a C++ compiler error, but
it's confusing.

This patch moves the error to the compiler, allowing the user to more
readily act to correct the issue.

Co-authored-by: Michael Beardsworth <beardsworth@intrinsic.ai>
2024-04-05 12:27:43 -07:00
Fergus Henderson
f4a9c5325b Avoid ODR violations with flatbuffers::Verifier. (#8274)
Fix "One Definition Rule" violation when using flatbuffers::Verifier with
FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE defined in some compilation units
and not defined in other compilation units.

The fix is to make Verifier a template class, with a boolean template
parameter replacing the "#ifdef" conditionals; to rename it as
VerifierTemplate; and then to use "#ifdef" only for a "using" declaration
that defines the original name Verifier an an alias for the instantiated
template.  In this way, even if FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE is
defined in some compilation units and not in others, as long as clients
only reference flatbuffers::Verifier in .cc files, not header files, there
will be no ODR violation, since the only part whose definition varies is the
"using" declaration, which does not have external linkage.

There is still some possibility of clients creating ODR violations
if the client header files (rather than .cc files) reference
flatbuffers::Verifier.  To avoid that, this change also deprecates
FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE, and instead introduces
flatbuffers::SizeVerifier as a public name for the template instance with
the boolean parameter set to true, so that clients don't need to define
the macro at all.
2024-04-02 12:50:15 -07:00
Derek Bailey
8f2e1dbd88 Start Release workflow when published 2024-03-26 05:31:50 +00:00
Derek Bailey
595bf0007a FlatBuffers Version v24.3.25 2024-03-26 05:18:07 +00:00
mpawlowski-eyeo
0cfb7eb80b Fix handling non null-terminated string_views in LookupByKey (#8203)
* Reproduce the error in a unit test

Reproduces #8200

* Overload KeyCompareWithValue to work for string-like objects

This fixes #8200.

* Extra tests

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
2024-03-25 10:39:51 -07:00
Derek Bailey
67eb95de92 presubmit.yml: Use xcode 14.2
It appears the upgrade to xcode 14.3 broke the macos build on builkite.
The last good build was using xcode 14.2, so go back to this version
until the issue is resolved.
2024-03-12 00:16:04 +00:00
Thomas Hartwig
b1f617fcb2 Fix License (#8253)
The previous license value was not suitable for most software license scanners. Listing the actual license string in the package.json fixes this
2024-03-11 16:45:30 -07:00
Wouter van Oortmerssen
960cd4d635 Lobster: Support required fields 2024-03-08 21:31:55 -08:00
Derek Bailey
6ff9e90e7e FlatBuffers Version v24.3.7 2024-03-07 15:16:33 -08:00
Derek Bailey
5b32e8f5c2 : Don't depend on java version 2024-03-07 14:56:09 -08:00
Derek Bailey
0bed8cd4a0 FlatBuffers Version v24.3.6 2024-03-07 07:23:33 +00:00
Derek Bailey
7cd216c51e FlatBuffers Version v24.3.6 2024-03-07 06:52:51 +00:00
467 changed files with 16730 additions and 10814 deletions

View File

@@ -1,25 +1,16 @@
---
buildifier: latest
bazel: 6.4.0
platforms:
ubuntu1804:
matrix:
bazel:
- 7.x
- 8.x
tasks:
verify_ubuntu2004:
platform: ubuntu2004
bazel: ${{ bazel }}
environment:
CC: clang
SWIFT_VERSION: "5.5.3"
SWIFT_HOME: "$HOME/swift-$SWIFT_VERSION"
PATH: "$PATH:$SWIFT_HOME/usr/bin"
shell_commands:
- "echo --- Downloading and extracting Swift $SWIFT_VERSION to $SWIFT_HOME"
- "mkdir $SWIFT_HOME"
- "curl https://download.swift.org/swift-${SWIFT_VERSION}-release/ubuntu1804/swift-${SWIFT_VERSION}-RELEASE/swift-${SWIFT_VERSION}-RELEASE-ubuntu18.04.tar.gz | tar xvz --strip-components=1 -C $SWIFT_HOME"
build_targets:
- "//..."
test_targets:
- "//..."
ubuntu2004:
environment:
CC: clang
SWIFT_VERSION: "5.5.3"
SWIFT_VERSION: "5.9"
SWIFT_HOME: "$HOME/swift-$SWIFT_VERSION"
PATH: "$PATH:$SWIFT_HOME/usr/bin"
shell_commands:
@@ -30,8 +21,40 @@ platforms:
- "//..."
test_targets:
- "//..."
macos:
verify_ubuntu2204:
platform: ubuntu2204
bazel: ${{ bazel }}
environment:
CC: clang
SWIFT_VERSION: "5.9"
SWIFT_HOME: "$HOME/swift-$SWIFT_VERSION"
PATH: "$PATH:$SWIFT_HOME/usr/bin"
shell_commands:
- "echo --- Downloading and extracting Swift $SWIFT_VERSION to $SWIFT_HOME"
- "mkdir $SWIFT_HOME"
- "curl https://download.swift.org/swift-${SWIFT_VERSION}-release/ubuntu2204/swift-${SWIFT_VERSION}-RELEASE/swift-${SWIFT_VERSION}-RELEASE-ubuntu22.04.tar.gz | tar xvz --strip-components=1 -C $SWIFT_HOME"
build_targets:
- "//..."
test_targets:
- "//..."
test_module_cpp:
platform: ubuntu2204
bazel: ${{ bazel }}
working_directory: tests/bazel_repository_test_dir
build_targets:
- "//..."
test_module_ts:
platform: ubuntu2204
bazel: ${{ bazel }}
working_directory: tests/ts/bazel_repository_test_dir
test_targets:
- "//..."
verify_macos:
platform: macos
bazel: ${{ bazel }}
xcode_version: "15.2"
build_targets:
- "//:flatbuffers"
- "//:flatc"
test_targets:
- "//tests:flatbuffers_test"

View File

@@ -1 +1,5 @@
node_modules
ts/node_modules
# Test workspaces
tests/bazel_repository_test_dir
tests/ts/bazel_repository_test_dir

View File

@@ -1,4 +1,18 @@
# We cannot use "common" here because the "version" command doesn't support
# --deleted_packages. We need to specify it for both build and query instead.
build --deleted_packages=tests/ts/bazel_repository_test_dir
query --deleted_packages=tests/ts/bazel_repository_test_dir
build --deleted_packages=tests/bazel_repository_test_dir,tests/ts/bazel_repository_test_dir
query --deleted_packages=tests/bazel_repository_test_dir,tests/ts/bazel_repository_test_dir
# Point tools such as coursier (used in rules_jvm_external) to Bazel's internal JDK
# suggested in https://github.com/bazelbuild/rules_jvm_external/issues/445
common --repo_env=JAVA_HOME=../bazel_tools/jdk
common --action_env=JAVA_HOME=../bazel_tools/jdk
# Workaround "Error: need --enable_runfiles on Windows for to support rules_js"
common:windows --enable_runfiles
# Swift is not required on Windows
common:windows --deleted_packages=swift
# Ignore warnings in external dependencies
build --per_file_copt=external/.*@-Wno-everything --host_per_file_copt=external/.*@-Wno-everything
# Honor the setting of `skipLibCheck` in the tsconfig.json file.
common --@aspect_rules_ts//ts:skipLibCheck=honor_tsconfig
# Use "tsc" as the transpiler when ts_project has no `transpiler` set.
common --@aspect_rules_ts//ts:default_to_tsc_transpiler

11
.github/ISSUE_TEMPLATE/404-doc.md vendored Normal file
View File

@@ -0,0 +1,11 @@
---
name: 404 Doc
about: To fix broken documentation links
title: "[Doc 404]"
labels: documentation
assignees: dbaileychess
---
Target URL:
[Optional] Source Site:

View File

@@ -12,6 +12,9 @@ on:
pull_request:
branches:
- master
schedule:
# Run daily at 4:45 A.M. to catch dependencies that break us.
- cron: '45 4 * * *'
jobs:
build-linux:
@@ -21,10 +24,10 @@ jobs:
digests-gcc: ${{ steps.hash-gcc.outputs.hashes }}
digests-clang: ${{ steps.hash-clang.outputs.hashes }}
name: Build Linux
runs-on: ubuntu-22.04-64core
runs-on: ubuntu-24.04
strategy:
matrix:
cxx: [g++-13, clang++-15]
cxx: [g++-13, clang++-18]
fail-fast: false
steps:
- uses: actions/checkout@v3
@@ -39,7 +42,7 @@ jobs:
chmod +x flatc
./flatc --version
- name: upload build artifacts
uses: actions/upload-artifact@v1
uses: actions/upload-artifact@v4
with:
name: Linux flatc binary ${{ matrix.cxx }}
path: flatc
@@ -53,7 +56,7 @@ jobs:
with:
files: Linux.flatc.binary.${{ matrix.cxx }}.zip
- name: Generate SLSA subjects - clang
if: matrix.cxx == 'clang++-15' && startsWith(github.ref, 'refs/tags/')
if: matrix.cxx == 'clang++-18' && startsWith(github.ref, 'refs/tags/')
id: hash-clang
run: echo "hashes=$(sha256sum Linux.flatc.binary.${{ matrix.cxx }}.zip | base64 -w0)" >> $GITHUB_OUTPUT
- name: Generate SLSA subjects - gcc
@@ -63,11 +66,11 @@ jobs:
build-linux-no-file-tests:
name: Build Linux with -DFLATBUFFERS_NO_FILE_TESTS
runs-on: ubuntu-22.04-64core
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v3
- name: cmake
run: CXX=clang++-15 cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON -DFLATBUFFERS_CXX_FLAGS="-DFLATBUFFERS_NO_FILE_TESTS" .
run: CXX=clang++-18 cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON -DFLATBUFFERS_CXX_FLAGS="-DFLATBUFFERS_NO_FILE_TESTS" .
- name: build
run: make -j
- name: test
@@ -75,7 +78,7 @@ jobs:
build-linux-out-of-source:
name: Build Linux with out-of-source build location
runs-on: ubuntu-22.04-64core
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v3
- name: make build directory
@@ -83,7 +86,7 @@ jobs:
- name: cmake
working-directory: build
run: >
CXX=clang++-15 cmake .. -G "Unix Makefiles" -DFLATBUFFERS_STRICT_MODE=ON
CXX=clang++-18 cmake .. -G "Unix Makefiles" -DFLATBUFFERS_STRICT_MODE=ON
-DFLATBUFFERS_BUILD_CPP17=ON -DFLATBUFFERS_CPP_STD=17
- name: build
working-directory: build
@@ -97,15 +100,15 @@ jobs:
build-linux-cpp-std:
name: Build Linux C++
runs-on: ubuntu-22.04-64core
runs-on: ubuntu-24.04
strategy:
fail-fast: false
matrix:
std: [11, 14, 17, 20, 23]
cxx: [g++-13, clang++-15]
cxx: [g++-13, clang++-18]
exclude:
# Clang++15 10.3.0 stdlibc++ doesn't fully support std 23
- cxx: clang++-15
- cxx: clang++-18
std: 23
steps:
@@ -167,7 +170,7 @@ jobs:
- name: test
run: Release\flattests.exe
- name: upload build artifacts
uses: actions/upload-artifact@v1
uses: actions/upload-artifact@v4
with:
name: Windows flatc binary
path: Release\flatc.exe
@@ -200,7 +203,7 @@ jobs:
steps:
- uses: actions/checkout@v3
- name: Setup .NET Core SDK
uses: actions/setup-dotnet@v3
uses: actions/setup-dotnet@v4.2.0
with:
dotnet-version: '8.0.x'
- name: Build
@@ -208,11 +211,16 @@ jobs:
cd tests\FlatBuffers.Test
dotnet new sln --force --name FlatBuffers.Test
dotnet sln FlatBuffers.Test.sln add FlatBuffers.Test.csproj
dotnet build -c Release ${{matrix.configuration}} -o out FlatBuffers.Test.sln
- name: Run
dotnet build -c Release ${{matrix.configuration}} FlatBuffers.Test.sln
- name: Run net6.0
run: |
cd tests\FlatBuffers.Test
out\FlatBuffers.Test.exe
cd tests\FlatBuffers.Test\bin\Release\net6.0
dir
.\FlatBuffers.Test.exe
- name: Run net8.0
run: |
cd tests\FlatBuffers.Test\bin\Release\net8.0
.\FlatBuffers.Test.exe
build-mac-intel:
permissions:
@@ -220,11 +228,11 @@ jobs:
outputs:
digests: ${{ steps.hash.outputs.hashes }}
name: Build Mac (for Intel)
runs-on: macos-latest
runs-on: macos-latest-large
steps:
- uses: actions/checkout@v3
- name: cmake
run: cmake -G "Xcode" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON .
run: cmake -G "Xcode" -DCMAKE_OSX_ARCHITECTURES="x86_64" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON .
- name: build
run: xcodebuild -toolchain clang -configuration Release -target flattests
- name: check that the binary is x86_64
@@ -239,9 +247,9 @@ jobs:
chmod +x Release/flatc
Release/flatc --version
- name: upload build artifacts
uses: actions/upload-artifact@v1
uses: actions/upload-artifact@v4
with:
name: Mac flatc binary
name: Mac flatc binary Intel
path: Release/flatc
# Below if only for release.
- name: Zip file
@@ -282,9 +290,9 @@ jobs:
chmod +x Release/flatc
Release/flatc --version
- name: upload build artifacts
uses: actions/upload-artifact@v1
uses: actions/upload-artifact@v4
with:
name: Mac flatc binary
name: Mac flatc binary Universal
path: Release/flatc
# Below if only for release.
- name: Zip file
@@ -302,7 +310,7 @@ jobs:
build-android:
name: Build Android (on Linux)
runs-on: ubuntu-22.04-64core
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v3
- name: set up Java
@@ -321,10 +329,10 @@ jobs:
build-generator:
name: Check Generated Code
runs-on: ubuntu-22.04-64core
runs-on: ubuntu-24.04
strategy:
matrix:
cxx: [g++-13, clang++-15]
cxx: [g++-13, clang++-18]
steps:
- uses: actions/checkout@v3
- name: cmake
@@ -352,7 +360,7 @@ jobs:
build-benchmarks:
name: Build Benchmarks (on Linux)
runs-on: ubuntu-22.04-64core
runs-on: ubuntu-24.04
strategy:
matrix:
cxx: [g++-13]
@@ -363,14 +371,14 @@ jobs:
- name: Run benchmarks
run: ./flatbenchmark --benchmark_repetitions=5 --benchmark_display_aggregates_only=true --benchmark_out_format=console --benchmark_out=benchmarks/results_${{matrix.cxx}}
- name: Upload benchmarks results
uses: actions/upload-artifact@v1
uses: actions/upload-artifact@v4
with:
name: Linux flatbenchmark results ${{matrix.cxx}}
path: benchmarks/results_${{matrix.cxx}}
build-java:
name: Build Java
runs-on: ubuntu-22.04-64core
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v3
- name: test
@@ -379,10 +387,17 @@ jobs:
build-kotlin-macos:
name: Build Kotlin MacOS
runs-on: macos-latest
runs-on: macos-13
steps:
- name: Checkout
uses: actions/checkout@v3
# Force Xcode 14.3 since Xcode 15 doesnt support older versions of
# kotlin. For Xcode 15, kotlin should be bumpped to 1.9.10
# https://stackoverflow.com/a/77150623
# For now, run with macos-13 which has this 14.3 installed:
# https://github.com/actions/runner-images/blob/main/images/macos/macos-13-Readme.md#xcode
- name: Set up Xcode version
run: sudo xcode-select -s /Applications/Xcode_14.3.app/Contents/Developer
- uses: gradle/wrapper-validation-action@v1.0.5
- uses: actions/setup-java@v3
with:
@@ -399,7 +414,7 @@ jobs:
build-kotlin-linux:
name: Build Kotlin Linux
runs-on: ubuntu-22.04-64core
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v3
@@ -422,7 +437,7 @@ jobs:
build-rust-linux:
name: Build Rust Linux
runs-on: ubuntu-22.04-64core
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v3
- name: test
@@ -440,7 +455,7 @@ jobs:
build-python:
name: Build Python
runs-on: ubuntu-22.04-64core
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v3
- name: flatc
@@ -452,7 +467,7 @@ jobs:
build-go:
name: Build Go
runs-on: ubuntu-22.04-64core
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v3
- name: flatc
@@ -464,7 +479,7 @@ jobs:
build-php:
name: Build PHP
runs-on: ubuntu-22.04-64core
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v3
- name: flatc
@@ -478,9 +493,18 @@ jobs:
build-swift:
name: Build Swift
runs-on: ubuntu-22.04-64core
strategy:
matrix:
swift: ["5.9", "5.10", "6.0"]
# Only 22.04 has swift at the moment https://github.com/actions/runner-images/blob/main/images/ubuntu/Ubuntu2204-Readme.md?plain=1#L30
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v3
- uses: swift-actions/setup-swift@v2
with:
swift-version: ${{ matrix.swift }}
- name: Get swift version
run: swift --version
- name: test
working-directory: tests/swift/tests
run: |
@@ -489,20 +513,22 @@ jobs:
build-swift-wasm:
name: Build Swift Wasm
runs-on: ubuntu-22.04-64core
runs-on: ubuntu-24.04
container:
image: ghcr.io/swiftwasm/carton:0.15.3
image: ghcr.io/swiftwasm/carton:0.20.1
steps:
- uses: actions/checkout@v3
- name: Setup Wasmer
uses: wasmerio/setup-wasmer@v2
- name: Test
working-directory: tests/swift/Wasm.tests
run: carton test
- uses: actions/checkout@v3
- uses: bytecodealliance/actions/wasmtime/setup@v1
- uses: swiftwasm/setup-swiftwasm@v1
with:
swift-version: "wasm-6.0.2-RELEASE"
- name: Test
working-directory: tests/swift/Wasm.tests
run: swift run carton test
build-ts:
name: Build TS
runs-on: ubuntu-22.04-64core
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v3
- name: flatc
@@ -520,7 +546,7 @@ jobs:
build-dart:
name: Build Dart
runs-on: ubuntu-22.04-64core
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v3
- uses: dart-lang/setup-dart@v1
@@ -535,7 +561,7 @@ jobs:
build-nim:
name: Build Nim
runs-on: ubuntu-22.04-64core
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v3
- name: flatc
@@ -549,12 +575,27 @@ jobs:
working-directory: tests/nim
run: python3 testnim.py
bazel:
name: Bazel
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v3
- name: bazel build
run: >
bazel build
//:flatc
//:flatbuffers
- name: bazel test
run: >
bazel test
//tests:flatbuffers_test
release-digests:
if: startsWith(github.ref, 'refs/tags/')
needs: [build-linux, build-windows, build-mac-intel, build-mac-universal]
outputs:
digests: ${{ steps.hash.outputs.digests }}
runs-on: ubuntu-22.04-64core
runs-on: ubuntu-24.04
steps:
- name: Merge results
id: hash

View File

@@ -1,71 +0,0 @@
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"
permissions: read-all
on:
push:
branches: [ master ]
pull_request:
# The branches below must be a subset of the branches above
branches: [ master ]
schedule:
- cron: '16 20 * * 0'
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ 'cpp' ]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
# Learn more about CodeQL language support at https://git.io/codeql-language-support
steps:
- name: Checkout repository
uses: actions/checkout@v3
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
# - name: Autobuild
# uses: github/codeql-action/autobuild@v2
# Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
- run: |
cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON .
make -j
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2

36
.github/workflows/docs.yml vendored Normal file
View File

@@ -0,0 +1,36 @@
name: docs
on:
# For manual pushes.
workflow_dispatch:
# Pushes to main that touch the documentation directory.
push:
branches:
- master
paths:
- 'docs/**'
permissions:
contents: write
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Configure Git Credentials
run: |
git config user.name github-actions[bot]
git config user.email 41898282+github-actions[bot]@users.noreply.github.com
- uses: actions/setup-python@v5
with:
python-version: 3.x
- run: echo "cache_id=$(date --utc '+%V')" >> $GITHUB_ENV
- uses: actions/cache@v4
with:
key: mkdocs-material-${{ env.cache_id }}
path: .cache
restore-keys: |
mkdocs-material-
- run: pip install mkdocs-material
- run: pip install mkdocs-redirects
- run: mkdocs gh-deploy --force -f docs/mkdocs.yml

View File

@@ -1,35 +0,0 @@
name: Build and unit tests that are more time consuming
permissions: read-all
on:
# For manual tests.
workflow_dispatch:
pull_request:
types:
- closed
schedule:
- cron: "30 20 * * *"
jobs:
build-linux-s390x:
name: Build Linux on s390x arch and run unit tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: uraimo/run-on-arch-action@v2
name: Run commands
id: runcmd
with:
arch: s390x
distro: ubuntu_latest
install: |
apt-get update -q -y
apt-get -y install cmake
apt-get -y install make
apt-get -y install g++
run: |
lscpu | grep Endian
cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release
make -j
./flattests

View File

@@ -1,7 +1,7 @@
name: OSS-Fuzz
permissions: read-all
on:
on:
pull_request:
branches:
- master
@@ -27,7 +27,7 @@ jobs:
language: c++
fuzz-seconds: 60
- name: Upload Crash
uses: actions/upload-artifact@v1
uses: actions/upload-artifact@v4
if: failure() && steps.build.outcome == 'success'
with:
name: artifacts

View File

@@ -5,7 +5,7 @@ on:
# For manual tests.
workflow_dispatch:
release:
types: [created]
types: [published]
jobs:
publish-npm:
@@ -97,9 +97,56 @@ jobs:
- name: Publish Maven
run: mvn --batch-mode clean deploy
env:
OSSRH_USERNAME: ${{ secrets.OSSRH_USERNAME }}
OSSRH_PASSWORD: ${{ secrets.OSSRH_TOKEN }}
OSSRH_USERNAME: ${{ secrets.OSSRH_USER_V2 }}
OSSRH_PASSWORD: ${{ secrets.OSSRH_TOKEN_V2 }}
MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }}
publish-maven-kotlin:
name: Publish Maven - Kotlin
runs-on: ubuntu-latest
defaults:
run:
working-directory: ./kotlin
steps:
- uses: actions/checkout@v3
- name: Set up Maven Central Repository
uses: actions/setup-java@v3
with:
java-version: '11'
distribution: 'adopt'
cache: 'maven'
server-id: ossrh
server-username: OSSRH_USERNAME
server-password: OSSRH_PASSWORD
gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }}
gpg-passphrase: MAVEN_GPG_PASSPHRASE # this needs to be an env var
- name: Publish Kotlin Library on Maven
run: ./gradlew publishAllPublicationsToSonatypeRepository
env:
OSSRH_USERNAME: ${{ secrets.OSSRH_USER_V2 }}
OSSRH_PASSWORD: ${{ secrets.OSSRH_TOKEN_V2 }}
MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }}
publish-crates:
name: Publish crates.io
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
- name: Publish Flatbuffers
uses: katyo/publish-crates@v2
with:
path: ./rust/flatbuffers
registry-token: ${{ secrets.CARGO_TOKEN }}
- name: Publish Flexbuffers
uses: katyo/publish-crates@v2
with:
path: ./rust/flexbuffers
registry-token: ${{ secrets.CARGO_TOKEN }}

View File

@@ -1,55 +0,0 @@
name: Scorecards supply-chain security
on:
# Only the default branch is supported.
branch_protection_rule:
schedule:
- cron: '21 2 * * 5'
push:
branches: [ master ]
# Declare default permissions as read only.
permissions: read-all
jobs:
analysis:
name: Scorecards analysis
runs-on: ubuntu-latest
permissions:
# Needed to upload the results to code-scanning dashboard.
security-events: write
actions: read
contents: read
steps:
- name: "Checkout code"
uses: actions/checkout@a12a3943b4bdde767164f792f33f40b04645d846 # v3.0.0
with:
persist-credentials: false
- name: "Run analysis"
uses: ossf/scorecard-action@ce330fde6b1a5c9c75b417e7efc510b822a35564 # v1.1.2
with:
results_file: results.sarif
results_format: sarif
# Read-only PAT token. To create it,
# follow the steps in https://github.com/ossf/scorecard-action#pat-token-creation.
repo_token: ${{ secrets.SCORECARD_READ_TOKEN }}
# Publish the results to enable scorecard badges. For more details, see
# https://github.com/ossf/scorecard-action#publishing-results.
# For private repositories, `publish_results` will automatically be set to `false`,
# regardless of the value entered here.
publish_results: true
# Upload the results as artifacts (optional).
- name: "Upload artifact"
uses: actions/upload-artifact@6673cd052c4cd6fcf4b4e6e60ea986c889389535 # v3.0.0
with:
name: SARIF file
path: results.sarif
retention-days: 5
# Upload the results to GitHub's code scanning dashboard.
- name: "Upload to code-scanning"
uses: github/codeql-action/upload-sarif@5f532563584d71fdef14ee64d17bafb34f751ce5 # v1.0.26
with:
sarif_file: results.sarif

4
.gitignore vendored
View File

@@ -153,3 +153,7 @@ cmake-build-debug/
_deps/
**/.gradle/**
kotlin/**/generated
MODULE.bazel.lock
# Ignore the generated docs
docs/site

View File

@@ -1,5 +1,3 @@
load("@aspect_rules_js//npm:defs.bzl", "npm_link_package")
load("@npm//:defs.bzl", "npm_link_all_packages")
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library")
licenses(["notice"])
@@ -8,13 +6,6 @@ package(
default_visibility = ["//visibility:public"],
)
npm_link_all_packages(name = "node_modules")
npm_link_package(
name = "node_modules/flatbuffers",
src = "//ts:flatbuffers",
)
exports_files([
"LICENSE",
"tsconfig.json",
@@ -37,11 +28,16 @@ config_setting(
filegroup(
name = "distribution",
srcs = [
".bazelignore",
".npmrc",
"BUILD.bazel",
"WORKSPACE",
"MODULE.bazel",
"build_defs.bzl",
"package.json",
"pnpm-lock.yaml",
"typescript.bzl",
"//grpc/src/compiler:distribution",
"//include/codegen:distribution",
"//reflection:distribution",
"//src:distribution",
"//ts:distribution",
@@ -125,15 +121,7 @@ filegroup(
# Library used by flatbuffer_cc_library rules.
cc_library(
name = "runtime_cc",
hdrs = [
"include/flatbuffers/base.h",
"include/flatbuffers/flatbuffers.h",
"include/flatbuffers/flexbuffers.h",
"include/flatbuffers/stl_emulation.h",
"include/flatbuffers/util.h",
"include/flatbuffers/vector.h",
"include/flatbuffers/verifier.h",
],
hdrs = ["//:public_headers"],
linkstatic = 1,
strip_include_prefix = "/include",
)

View File

@@ -4,6 +4,35 @@ All major or breaking changes will be documented in this file, as well as any
new features that should be highlighted. Minor fixes or improvements are not
necessarily listed.
## [25.2.10] (February 10 2025)(https://github.com/google/flatbuffers/releases/tag/v25.2.10)
* Removed the old documentation pages. The new one is live at https://flatbuffers.dev
* Swift version 6.0 support (#8414)
## [25.1.24] (January 24 2025)(https://github.com/google/flatbuffers/releases/tag/v25.1.24)
* Mostly related to bazel build support.
* Min bazel supported is now 7 or higher, as WORKSPACE files are removed (#8509)
* Minor C++ codegen fix removing extra semicolon (#8488)
## [25.1.21] (January 21 2025)(https://github.com/google/flatbuffers/releases/tag/v25.1.21)
* Rust Full Reflection (#8102)
* Mostly documentation updates hosted at https://flatbuffers.dev
## [24.3.25] (March 25 2024)(https://github.com/google/flatbuffers/releases/tag/v24.3.25)
* Fixed license metadata parsing (#8253)
* [C++] Allow string_view in `LookUpByKey` in addition to null-terminated c-style strings (#8203)
## [24.3.7] (March 7 2024)(https://github.com/google/flatbuffers/releases/tag/v24.3.7)
* Just to fix some of the CI build issues from the 24.3.6 release.
## [24.3.6] (March 6 2024)(https://github.com/google/flatbuffers/releases/tag/v24.3.6)
* Fix typescript object API to allow 0 values for null-default scalars (#7864)
## [23.5.26 (May 26 2023)](https://github.com/google/flatbuffers/releases/tag/v23.5.26)
* Mostly bug fixing for 64-bit support

View File

@@ -1,6 +1,6 @@
set(VERSION_MAJOR 23)
set(VERSION_MINOR 5)
set(VERSION_PATCH 26)
set(VERSION_MAJOR 25)
set(VERSION_MINOR 2)
set(VERSION_PATCH 10)
set(VERSION_COMMIT 0)
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/.git")

View File

@@ -183,6 +183,10 @@ set(FlatBuffers_Compiler_SRCS
src/bfbs_gen_lua.h
src/bfbs_gen_nim.h
src/bfbs_namer.h
include/codegen/idl_namer.h
include/codegen/namer.h
include/codegen/python.h
include/codegen/python.cc
include/flatbuffers/code_generators.h
src/binary_annotator.h
src/binary_annotator.cpp

View File

@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'FlatBuffers'
s.version = '23.5.26'
s.version = '25.2.10'
s.summary = 'FlatBuffers: Memory Efficient Serialization Library'
s.description = "FlatBuffers is a cross platform serialization library architected for
@@ -10,12 +10,15 @@ Pod::Spec.new do |s|
s.homepage = 'https://github.com/google/flatbuffers'
s.license = { :type => 'Apache2.0', :file => 'LICENSE' }
s.author = { 'mustii' => 'mustii@mmk.one' }
s.source = { :git => 'https://github.com/google/flatbuffers.git', :tag => s.version.to_s, :submodules => true }
s.author = { 'mustii' => 'me@mustiikhalil.se' }
s.source = { :git => 'https://github.com/google/flatbuffers.git', :tag => "v" + s.version.to_s, :submodules => true }
s.ios.deployment_target = '11.0'
s.osx.deployment_target = '10.14'
s.swift_version = '5.0'
s.source_files = 'swift/Sources/Flatbuffers/*.swift'
s.pod_target_xcconfig = {
'BUILD_LIBRARY_FOR_DISTRIBUTION' => 'YES'
}
end

77
MODULE.bazel Normal file
View File

@@ -0,0 +1,77 @@
module(
name = "flatbuffers",
version = "25.2.10",
compatibility_level = 1,
repo_name = "com_github_google_flatbuffers",
)
bazel_dep(
name = "aspect_bazel_lib",
version = "2.11.0",
)
bazel_dep(
name = "aspect_rules_esbuild",
version = "0.21.0",
)
bazel_dep(
name = "aspect_rules_js",
version = "2.1.3",
)
bazel_dep(
name = "aspect_rules_ts",
version = "3.4.0",
)
bazel_dep(
name = "grpc",
version = "1.70.1",
repo_name = "com_github_grpc_grpc",
)
bazel_dep(
name = "platforms",
version = "0.0.10",
)
bazel_dep(
name = "rules_cc",
version = "0.0.16",
)
bazel_dep(
name = "rules_go",
version = "0.50.1",
repo_name = "io_bazel_rules_go",
)
bazel_dep(
name = "rules_nodejs",
version = "6.3.3",
)
bazel_dep(
name = "rules_shell",
version = "0.3.0",
)
bazel_dep(
name = "rules_swift",
version = "2.1.1",
repo_name = "build_bazel_rules_swift",
)
bazel_dep(
name = "bazel_skylib",
version = "1.7.1",
)
npm = use_extension("@aspect_rules_js//npm:extensions.bzl", "npm")
npm.npm_translate_lock(
name = "flatbuffers_npm",
npmrc = "//:.npmrc",
pnpm_lock = "//ts:pnpm-lock.yaml",
# Override the Bazel package where pnpm-lock.yaml is located and link
# to the specified package instead.
root_package = "ts",
verify_node_modules_ignored = "//:.bazelignore",
)
use_repo(npm, "flatbuffers_npm")
node = use_extension("@rules_nodejs//nodejs:extensions.bzl", "node")
use_repo(node, "nodejs_linux_amd64")
rules_ts_ext = use_extension("@aspect_rules_ts//ts:extensions.bzl", "ext")
rules_ts_ext.deps()
use_repo(rules_ts_ext, "npm_typescript")

View File

@@ -1,4 +1,4 @@
// swift-tools-version:5.6
// swift-tools-version:5.9
/*
* Copyright 2020 Google Inc. All rights reserved.
*

View File

@@ -1,37 +0,0 @@
// swift-tools-version:5.5
/*
* Copyright 2020 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 PackageDescription
let package = Package(
name: "FlatBuffers",
platforms: [
.iOS(.v11),
.macOS(.v10_14),
],
products: [
.library(
name: "FlatBuffers",
targets: ["FlatBuffers"]),
],
targets: [
.target(
name: "FlatBuffers",
dependencies: [],
path: "swift/Sources"),
])

View File

@@ -4,8 +4,6 @@
![Build status](https://github.com/google/flatbuffers/actions/workflows/build.yml/badge.svg?branch=master)
[![BuildKite status](https://badge.buildkite.com/7979d93bc6279aa539971f271253c65d5e8fe2fe43c90bbb25.svg)](https://buildkite.com/bazel/flatbuffers)
[![Fuzzing Status](https://oss-fuzz-build-logs.storage.googleapis.com/badges/flatbuffers.svg)](https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&can=1&q=proj:flatbuffers)
[![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/google/flatbuffers/badge)](https://api.securityscorecards.dev/projects/github.com/google/flatbuffers)
[![Join the chat at https://gitter.im/google/flatbuffers](https://badges.gitter.im/google/flatbuffers.svg)](https://gitter.im/google/flatbuffers?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Discord Chat](https://img.shields.io/discord/656202785926152206.svg)](https:///discord.gg/6qgKs3R)
[![Twitter Follow](https://img.shields.io/twitter/follow/wvo.svg?style=social)](https://twitter.com/wvo)
[![Twitter Follow](https://img.shields.io/twitter/follow/dbaileychess.svg?style=social)](https://twitter.com/dbaileychess)
@@ -18,7 +16,7 @@ maximum memory efficiency. It allows you to directly access serialized data with
1. Build the compiler for flatbuffers (`flatc`)
Use `cmake` to create the build files for your platform and then perform the compliation (Linux example).
Use `cmake` to create the build files for your platform and then perform the compilation (Linux example).
```
cmake -G "Unix Makefiles"

169
WORKSPACE
View File

@@ -1,169 +0,0 @@
workspace(name = "com_github_google_flatbuffers")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive", "http_file")
http_archive(
name = "platforms",
sha256 = "3a561c99e7bdbe9173aa653fd579fe849f1d8d67395780ab4770b1f381431d51",
urls = [
"https://mirror.bazel.build/github.com/bazelbuild/platforms/releases/download/0.0.7/platforms-0.0.7.tar.gz",
"https://github.com/bazelbuild/platforms/releases/download/0.0.7/platforms-0.0.7.tar.gz",
],
)
http_archive(
name = "build_bazel_rules_apple",
sha256 = "34c41bfb59cdaea29ac2df5a2fa79e5add609c71bb303b2ebb10985f93fa20e7",
url = "https://github.com/bazelbuild/rules_apple/releases/download/3.1.1/rules_apple.3.1.1.tar.gz",
)
load(
"@build_bazel_rules_apple//apple:repositories.bzl",
"apple_rules_dependencies",
)
apple_rules_dependencies()
http_archive(
name = "build_bazel_rules_swift",
sha256 = "a2fd565e527f83fb3f9eb07eb9737240e668c9242d3bc318712efa54a7deda97",
url = "https://github.com/bazelbuild/rules_swift/releases/download/0.27.0/rules_swift.0.27.0.tar.gz",
)
load(
"@build_bazel_rules_swift//swift:repositories.bzl",
"swift_rules_dependencies",
)
swift_rules_dependencies()
load(
"@build_bazel_rules_swift//swift:extras.bzl",
"swift_rules_extra_dependencies",
)
swift_rules_extra_dependencies()
http_archive(
name = "io_bazel_rules_go",
sha256 = "278b7ff5a826f3dc10f04feaf0b70d48b68748ccd512d7f98bf442077f043fe3",
urls = [
"https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.41.0/rules_go-v0.41.0.zip",
"https://github.com/bazelbuild/rules_go/releases/download/v0.41.0/rules_go-v0.41.0.zip",
],
)
load("@io_bazel_rules_go//go:deps.bzl", "go_rules_dependencies")
go_rules_dependencies()
##### Protobuf
_PROTOBUF_VERSION = "3.15.2"
http_archive(
name = "com_google_protobuf",
strip_prefix = "protobuf-" + _PROTOBUF_VERSION,
urls = [
"https://github.com/protocolbuffers/protobuf/archive/v" + _PROTOBUF_VERSION + ".tar.gz",
],
)
##### GRPC
_GRPC_VERSION = "1.49.0" # https://github.com/grpc/grpc/releases/tag/v1.48.0
http_archive(
name = "com_github_grpc_grpc",
patch_args = ["-p1"],
patches = ["//grpc:build_grpc_with_cxx14.patch"],
sha256 = "15715e1847cc9e42014f02c727dbcb48e39dbdb90f79ad3d66fe4361709ff935",
strip_prefix = "grpc-" + _GRPC_VERSION,
urls = ["https://github.com/grpc/grpc/archive/refs/tags/v" + _GRPC_VERSION + ".tar.gz"],
)
load("@com_github_grpc_grpc//bazel:grpc_deps.bzl", "grpc_deps")
grpc_deps()
load("@com_github_grpc_grpc//bazel:grpc_extra_deps.bzl", "grpc_extra_deps")
grpc_extra_deps()
# rules_go from https://github.com/bazelbuild/rules_go/releases/tag/v0.34.0
http_archive(
name = "aspect_rules_js",
sha256 = "76a04ef2120ee00231d85d1ff012ede23963733339ad8db81f590791a031f643",
strip_prefix = "rules_js-1.34.1",
url = "https://github.com/aspect-build/rules_js/releases/download/v1.34.1/rules_js-v1.34.1.tar.gz",
)
load("@aspect_rules_js//js:repositories.bzl", "rules_js_dependencies")
rules_js_dependencies()
load("@aspect_rules_js//npm:npm_import.bzl", "npm_translate_lock", "pnpm_repository")
pnpm_repository(name = "pnpm")
http_archive(
name = "aspect_rules_ts",
sha256 = "4c3f34fff9f96ffc9c26635d8235a32a23a6797324486c7d23c1dfa477e8b451",
strip_prefix = "rules_ts-1.4.5",
url = "https://github.com/aspect-build/rules_ts/releases/download/v1.4.5/rules_ts-v1.4.5.tar.gz",
)
load("@aspect_rules_ts//ts:repositories.bzl", "rules_ts_dependencies")
rules_ts_dependencies(
# Since rules_ts doesn't always have the newest integrity hashes, we
# compute it manually here.
# $ curl --silent https://registry.npmjs.org/typescript/5.3.3 | jq ._integrity
ts_integrity = "sha512-pXWcraxM0uxAS+tN0AG/BF2TyqmHO014Z070UsJ+pFvYuRSq8KH8DmWpnbXe0pEPDHXZV3FcAbJkijJ5oNEnWw==",
ts_version_from = "//:package.json",
)
load("@rules_nodejs//nodejs:repositories.bzl", "DEFAULT_NODE_VERSION", "nodejs_register_toolchains")
nodejs_register_toolchains(
name = "nodejs",
node_version = DEFAULT_NODE_VERSION,
)
npm_translate_lock(
name = "npm",
npmrc = "//:.npmrc",
pnpm_lock = "//:pnpm-lock.yaml",
# Set this to True when the lock file needs to be updated, commit the
# changes, then set to False again.
update_pnpm_lock = False,
verify_node_modules_ignored = "//:.bazelignore",
)
load("@npm//:repositories.bzl", "npm_repositories")
npm_repositories()
http_archive(
name = "aspect_rules_esbuild",
sha256 = "098e38e5ee868c14a6484ba263b79e57d48afacfc361ba30137c757a9c4716d6",
strip_prefix = "rules_esbuild-0.15.0",
url = "https://github.com/aspect-build/rules_esbuild/releases/download/v0.15.0/rules_esbuild-v0.15.0.tar.gz",
)
# Register a toolchain containing esbuild npm package and native bindings
load("@aspect_rules_esbuild//esbuild:repositories.bzl", "LATEST_ESBUILD_VERSION", "esbuild_register_toolchains")
esbuild_register_toolchains(
name = "esbuild",
esbuild_version = LATEST_ESBUILD_VERSION,
)
http_file(
name = "bazel_linux_x86_64",
downloaded_file_path = "bazel",
executable = True,
sha256 = "e78fc3394deae5408d6f49a15c7b1e615901969ecf6e50d55ef899996b0b8458",
urls = [
"https://github.com/bazelbuild/bazel/releases/download/6.3.2/bazel-6.3.2-linux-x86_64",
],
)

View File

@@ -8,9 +8,9 @@
// Ensure the included flatbuffers.h is the same version as when this file was
// generated, otherwise it may not be compatible.
static_assert(FLATBUFFERS_VERSION_MAJOR == 23 &&
FLATBUFFERS_VERSION_MINOR == 1 &&
FLATBUFFERS_VERSION_REVISION == 21,
static_assert(FLATBUFFERS_VERSION_MAJOR == 24 &&
FLATBUFFERS_VERSION_MINOR == 12 &&
FLATBUFFERS_VERSION_REVISION == 23,
"Non-compatible flatbuffers version included");
namespace com {

View File

@@ -57,7 +57,7 @@ class Animal : Table() {
return if(o != 0) bb.getShort(o + bb_pos).toUShort() else 0u
}
companion object {
fun validateVersion() = Constants.FLATBUFFERS_23_5_26()
fun validateVersion() = Constants.FLATBUFFERS_25_2_10()
fun getRootAsAnimal(_bb: ByteBuffer): Animal = getRootAsAnimal(_bb, Animal())
fun getRootAsAnimal(_bb: ByteBuffer, obj: Animal): Animal {
_bb.order(ByteOrder.LITTLE_ENDIAN)

View File

@@ -8,9 +8,9 @@
// Ensure the included flatbuffers.h is the same version as when this file was
// generated, otherwise it may not be compatible.
static_assert(FLATBUFFERS_VERSION_MAJOR == 2 &&
FLATBUFFERS_VERSION_MINOR == 0 &&
FLATBUFFERS_VERSION_REVISION == 6,
static_assert(FLATBUFFERS_VERSION_MAJOR == 24 &&
FLATBUFFERS_VERSION_MINOR == 12 &&
FLATBUFFERS_VERSION_REVISION == 23,
"Non-compatible flatbuffers version included");
namespace benchmarks_flatbuffers {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2023 Google Inc. All rights reserved.
* Copyright 2024 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.
@@ -178,4 +178,24 @@ let benchmarks = {
let root = Offset(offset: fb.endTable(at: start))
fb.finish(offset: root)
}
Benchmark("Vector of Offsets") { benchmark in
let rawSize = ((16 * 5) * benchmark.scaledIterations.count) / 1024
var fb = FlatBufferBuilder(initialSize: Int32(rawSize * 1600))
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
let offsets = [
fb.create(string: "T"),
fb.create(string: "2"),
fb.create(string: "3"),
]
let off = fb.createVector(ofOffsets: [
fb.createVector(ofOffsets: offsets),
fb.createVector(ofOffsets: offsets),
])
let s = fb.startTable(with: 2)
fb.add(offset: off, at: 2)
blackHole(fb.endTable(at: s))
}
}
}

View File

@@ -1,4 +1,4 @@
// swift-tools-version:5.8
// swift-tools-version:5.9
/*
* Copyright 2020 Google Inc. All rights reserved.
*
@@ -26,7 +26,7 @@ let package = Package(
.package(path: "../.."),
.package(
url: "https://github.com/ordo-one/package-benchmark",
from: "1.12.0"),
from: "1.27.0"),
],
targets: [
.executableTarget(

View File

@@ -7,13 +7,13 @@ Rules for building C++ flatbuffers with Bazel.
load("@rules_cc//cc:defs.bzl", "cc_library")
TRUE_FLATC_PATH = "@com_github_google_flatbuffers//:flatc"
TRUE_FLATC_PATH = Label("//:flatc")
DEFAULT_INCLUDE_PATHS = [
"./",
"$(GENDIR)",
"$(BINDIR)",
"$(execpath @com_github_google_flatbuffers//:flatc).runfiles/com_github_google_flatbuffers",
"$(execpath %s).runfiles/%s" % (TRUE_FLATC_PATH, TRUE_FLATC_PATH.repo_name),
]
def default_include_paths(flatc_path):
@@ -21,7 +21,7 @@ def default_include_paths(flatc_path):
"./",
"$(GENDIR)",
"$(BINDIR)",
"$(execpath %s).runfiles/com_github_google_flatbuffers" % (flatc_path),
"$(execpath %s).runfiles/%s" % (flatc_path, flatc_path.repo_name),
]
DEFAULT_FLATC_ARGS = [
@@ -47,7 +47,7 @@ def flatbuffer_library_public(
compatible_with = None,
restricted_to = None,
target_compatible_with = None,
flatc_path = "@com_github_google_flatbuffers//:flatc",
flatc_path = None,
output_to_bindir = False,
tools = None,
extra_env = None,
@@ -87,6 +87,11 @@ def flatbuffer_library_public(
optionally a Fileset([reflection_name]) with all generated reflection
binaries.
"""
if flatc_path == None:
flatc_path = TRUE_FLATC_PATH
else:
flatc_path = native.package_relative_label(flatc_path)
reflection_include_paths = include_paths
if include_paths == None:
include_paths = default_include_paths(flatc_path)
@@ -131,6 +136,8 @@ def flatbuffer_library_public(
reflection_genrule_cmd = " ".join([
"SRCS=($(SRCS));",
"for f in $${SRCS[@]:0:%s}; do" % len(srcs),
# Move the .fbs file into the current package if it is not there already
'if [[ $$(dirname $$f) != "{0}" ]]; then s="$$f"; f="{0}/$$(basename "$$f")"; mkdir -p "{0}"; mv "$$s" "$$f"; fi;'.format(native.package_relative_label(":invalid").package),
"$(location %s)" % (TRUE_FLATC_PATH),
"-b --schema",
" ".join(flatc_args),
@@ -141,9 +148,10 @@ def flatbuffer_library_public(
"done",
])
reflection_outs = [
(out_prefix + "%s.bfbs") % (s.replace(".fbs", "").split("/")[-1])
(out_prefix + "%s.bfbs") % (native.package_relative_label(s).name.removesuffix(".fbs"))
for s in srcs
]
native.genrule(
name = "%s_srcs" % reflection_name,
srcs = srcs + includes,
@@ -262,8 +270,8 @@ def flatbuffer_cc_library(
"-parse_headers",
],
deps = [
"@com_github_google_flatbuffers//:runtime_cc",
"@com_github_google_flatbuffers//:flatbuffers",
Label("//:runtime_cc"),
Label("//:flatbuffers"),
] + deps,
includes = cc_include_paths,
compatible_with = compatible_with,

View File

@@ -386,7 +386,7 @@ class Builder {
/// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer.
void putFloat64(double value) {
_prepare(_sizeofFloat64, 1);
_setFloat32AtTail(_tail, value);
_setFloat64AtTail(_tail, value);
}
/// Writes a Float32 to the tail of the buffer after preparing space for it.

View File

@@ -1,11 +1,11 @@
name: flat_buffers
version: 23.5.26
version: 25.2.10
description: FlatBuffers reading and writing library for Dart. Based on original work by Konstantin Scheglov and Paul Berry of the Dart SDK team.
homepage: https://github.com/google/flatbuffers
documentation: https://google.github.io/flatbuffers/index.html
environment:
sdk: '>=2.12.0 <4.0.0'
sdk: '>=2.17.0 <4.0.0'
dev_dependencies:
test: ^1.17.7

View File

@@ -1,5 +1,5 @@
// automatically generated by the FlatBuffers compiler, do not modify
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names
import 'dart:typed_data' show Uint8List;
import 'package:flat_buffers/flat_buffers.dart' as fb;

View File

@@ -1,43 +1,33 @@
// automatically generated by the FlatBuffers compiler, do not modify
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names
import 'dart:typed_data' show Uint8List;
import 'package:flat_buffers/flat_buffers.dart' as fb;
class OptionsEnum {
enum OptionsEnum {
A(1),
B(2),
C(3);
final int value;
const OptionsEnum._(this.value);
const OptionsEnum(this.value);
factory OptionsEnum.fromValue(int value) {
final result = values[value];
if (result == null) {
throw StateError('Invalid value $value for bit flag enum OptionsEnum');
switch (value) {
case 1: return OptionsEnum.A;
case 2: return OptionsEnum.B;
case 3: return OptionsEnum.C;
default: throw StateError('Invalid value $value for bit flag enum');
}
return result;
}
static OptionsEnum? _createOrNull(int? value) =>
static OptionsEnum? _createOrNull(int? value) =>
value == null ? null : OptionsEnum.fromValue(value);
static const int minValue = 1;
static const int maxValue = 3;
static bool containsValue(int value) => values.containsKey(value);
static const OptionsEnum A = OptionsEnum._(1);
static const OptionsEnum B = OptionsEnum._(2);
static const OptionsEnum C = OptionsEnum._(3);
static const Map<int, OptionsEnum> values = {
1: A,
2: B,
3: C};
static const fb.Reader<OptionsEnum> reader = _OptionsEnumReader();
@override
String toString() {
return 'OptionsEnum{value: $value}';
}
}
class _OptionsEnumReader extends fb.Reader<OptionsEnum> {

View File

@@ -9,7 +9,7 @@ import 'package:test_reflective_loader/test_reflective_loader.dart';
import './monster_test_my_game.example_generated.dart' as example;
import './monster_test_my_game.example2_generated.dart' as example2;
import './list_of_enums_generated.dart' as example3;
import 'enums_generated.dart' as example3;
import './bool_structs_generated.dart' as example4;
main() {
@@ -63,11 +63,11 @@ class CheckOtherLangaugesData {
expect(
mon.toString(),
'Monster{'
'pos: Vec3{x: 1.0, y: 2.0, z: 3.0, test1: 3.0, test2: Color{value: 2}, test3: Test{a: 5, b: 6}}, '
'pos: Vec3{x: 1.0, y: 2.0, z: 3.0, test1: 3.0, test2: Color.Green, test3: Test{a: 5, b: 6}}, '
'mana: 150, hp: 80, name: MyMonster, inventory: [0, 1, 2, 3, 4], '
'color: Color{value: 8}, testType: AnyTypeId{value: 1}, '
'color: Color.Blue, testType: AnyTypeId.Monster, '
'test: Monster{pos: null, mana: 150, hp: 100, name: Fred, '
'inventory: null, color: Color{value: 8}, testType: null, '
'inventory: null, color: Color.Blue, testType: null, '
'test: null, test4: null, testarrayofstring: null, '
'testarrayoftables: null, enemy: null, testnestedflatbuffer: null, '
'testempty: null, testbool: false, testhashs32Fnv1: 0, '
@@ -82,18 +82,18 @@ class CheckOtherLangaugesData {
'coOwningReference: 0, vectorOfCoOwningReferences: null, '
'nonOwningReference: 0, vectorOfNonOwningReferences: null, '
'anyUniqueType: null, anyUnique: null, anyAmbiguousType: null, '
'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race{value: -1}, '
'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race.None, '
'testrequirednestedflatbuffer: null, scalarKeySortedTables: null, '
'nativeInline: null, '
'longEnumNonEnumDefault: LongEnum{value: 0}, '
'longEnumNormalDefault: LongEnum{value: 2}, nanDefault: NaN, '
'longEnumNonEnumDefault: LongEnum._default, '
'longEnumNormalDefault: LongEnum.LongOne, nanDefault: NaN, '
'infDefault: Infinity, positiveInfDefault: Infinity, infinityDefault: '
'Infinity, positiveInfinityDefault: Infinity, negativeInfDefault: '
'-Infinity, negativeInfinityDefault: -Infinity, doubleInfDefault: Infinity}, '
'test4: [Test{a: 10, b: 20}, Test{a: 30, b: 40}], '
'testarrayofstring: [test1, test2], testarrayoftables: null, '
'enemy: Monster{pos: null, mana: 150, hp: 100, name: Fred, '
'inventory: null, color: Color{value: 8}, testType: null, '
'inventory: null, color: Color.Blue, testType: null, '
'test: null, test4: null, testarrayofstring: null, '
'testarrayoftables: null, enemy: null, testnestedflatbuffer: null, '
'testempty: null, testbool: false, testhashs32Fnv1: 0, '
@@ -108,11 +108,11 @@ class CheckOtherLangaugesData {
'coOwningReference: 0, vectorOfCoOwningReferences: null, '
'nonOwningReference: 0, vectorOfNonOwningReferences: null, '
'anyUniqueType: null, anyUnique: null, anyAmbiguousType: null, '
'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race{value: -1}, '
'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race.None, '
'testrequirednestedflatbuffer: null, scalarKeySortedTables: null, '
'nativeInline: null, '
'longEnumNonEnumDefault: LongEnum{value: 0}, '
'longEnumNormalDefault: LongEnum{value: 2}, nanDefault: NaN, '
'longEnumNonEnumDefault: LongEnum._default, '
'longEnumNormalDefault: LongEnum.LongOne, nanDefault: NaN, '
'infDefault: Infinity, positiveInfDefault: Infinity, infinityDefault: '
'Infinity, positiveInfinityDefault: Infinity, negativeInfDefault: '
'-Infinity, negativeInfinityDefault: -Infinity, doubleInfDefault: Infinity}, '
@@ -137,12 +137,12 @@ class CheckOtherLangaugesData {
'vectorOfNonOwningReferences: null, '
'anyUniqueType: null, anyUnique: null, '
'anyAmbiguousType: null, '
'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race{value: -1}, '
'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race.None, '
'testrequirednestedflatbuffer: null, scalarKeySortedTables: [Stat{id: '
'miss, val: 0, count: 0}, Stat{id: hit, val: 10, count: 1}], '
'nativeInline: Test{a: 1, b: 2}, '
'longEnumNonEnumDefault: LongEnum{value: 0}, '
'longEnumNormalDefault: LongEnum{value: 2}, nanDefault: NaN, '
'longEnumNonEnumDefault: LongEnum._default, '
'longEnumNormalDefault: LongEnum.LongOne, nanDefault: NaN, '
'infDefault: Infinity, positiveInfDefault: Infinity, infinityDefault: '
'Infinity, positiveInfinityDefault: Infinity, negativeInfDefault: '
'-Infinity, negativeInfinityDefault: -Infinity, doubleInfDefault: Infinity}');
@@ -215,6 +215,10 @@ class BuilderTest {
..addTestarrayofstringOffset(testArrayOfString);
final mon = monBuilder.finish();
fbBuilder.finish(mon);
final mon3 = example.Monster(fbBuilder.buffer);
expect(mon3.name, 'MyMonster');
expect(mon3.pos!.test1, 3.0);
}
void test_error_addInt32_withoutStartTable([Builder? builder]) {

View File

@@ -1,5 +1,5 @@
// automatically generated by the FlatBuffers compiler, do not modify
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names
import 'dart:typed_data' show Uint8List;
import 'package:flat_buffers/flat_buffers.dart' as fb;

View File

@@ -1,5 +1,5 @@
// automatically generated by the FlatBuffers compiler, do not modify
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names
library my_game.other_name_space;
@@ -9,35 +9,25 @@ import 'package:flat_buffers/flat_buffers.dart' as fb;
import './include_test1_generated.dart';
class FromInclude {
enum FromInclude {
IncludeVal(0);
final int value;
const FromInclude._(this.value);
const FromInclude(this.value);
factory FromInclude.fromValue(int value) {
final result = values[value];
if (result == null) {
throw StateError('Invalid value $value for bit flag enum FromInclude');
switch (value) {
case 0: return FromInclude.IncludeVal;
default: throw StateError('Invalid value $value for bit flag enum');
}
return result;
}
static FromInclude? _createOrNull(int? value) =>
static FromInclude? _createOrNull(int? value) =>
value == null ? null : FromInclude.fromValue(value);
static const int minValue = 0;
static const int maxValue = 0;
static bool containsValue(int value) => values.containsKey(value);
static const FromInclude IncludeVal = FromInclude._(0);
static const Map<int, FromInclude> values = {
0: IncludeVal};
static const fb.Reader<FromInclude> reader = _FromIncludeReader();
@override
String toString() {
return 'FromInclude{value: $value}';
}
}
class _FromIncludeReader extends fb.Reader<FromInclude> {

View File

@@ -1,5 +1,5 @@
// automatically generated by the FlatBuffers compiler, do not modify
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names
library keyword_test;
@@ -7,39 +7,29 @@ import 'dart:typed_data' show Uint8List;
import 'package:flat_buffers/flat_buffers.dart' as fb;
class Abc {
enum Abc {
$void(0),
where(1),
stackalloc(2);
final int value;
const Abc._(this.value);
const Abc(this.value);
factory Abc.fromValue(int value) {
final result = values[value];
if (result == null) {
throw StateError('Invalid value $value for bit flag enum Abc');
switch (value) {
case 0: return Abc.$void;
case 1: return Abc.where;
case 2: return Abc.stackalloc;
default: throw StateError('Invalid value $value for bit flag enum');
}
return result;
}
static Abc? _createOrNull(int? value) =>
static Abc? _createOrNull(int? value) =>
value == null ? null : Abc.fromValue(value);
static const int minValue = 0;
static const int maxValue = 2;
static bool containsValue(int value) => values.containsKey(value);
static const Abc $void = Abc._(0);
static const Abc where = Abc._(1);
static const Abc stackalloc = Abc._(2);
static const Map<int, Abc> values = {
0: $void,
1: where,
2: stackalloc};
static const fb.Reader<Abc> reader = _AbcReader();
@override
String toString() {
return 'Abc{value: $value}';
}
}
class _AbcReader extends fb.Reader<Abc> {
@@ -53,35 +43,25 @@ class _AbcReader extends fb.Reader<Abc> {
Abc.fromValue(const fb.Int32Reader().read(bc, offset));
}
class Public {
enum Public {
NONE(0);
final int value;
const Public._(this.value);
const Public(this.value);
factory Public.fromValue(int value) {
final result = values[value];
if (result == null) {
throw StateError('Invalid value $value for bit flag enum Public');
switch (value) {
case 0: return Public.NONE;
default: throw StateError('Invalid value $value for bit flag enum');
}
return result;
}
static Public? _createOrNull(int? value) =>
static Public? _createOrNull(int? value) =>
value == null ? null : Public.fromValue(value);
static const int minValue = 0;
static const int maxValue = 0;
static bool containsValue(int value) => values.containsKey(value);
static const Public NONE = Public._(0);
static const Map<int, Public> values = {
0: NONE};
static const fb.Reader<Public> reader = _PublicReader();
@override
String toString() {
return 'Public{value: $value}';
}
}
class _PublicReader extends fb.Reader<Public> {
@@ -95,39 +75,29 @@ class _PublicReader extends fb.Reader<Public> {
Public.fromValue(const fb.Int32Reader().read(bc, offset));
}
class KeywordsInUnionTypeId {
enum KeywordsInUnionTypeId {
NONE(0),
$static(1),
internal(2);
final int value;
const KeywordsInUnionTypeId._(this.value);
const KeywordsInUnionTypeId(this.value);
factory KeywordsInUnionTypeId.fromValue(int value) {
final result = values[value];
if (result == null) {
throw StateError('Invalid value $value for bit flag enum KeywordsInUnionTypeId');
switch (value) {
case 0: return KeywordsInUnionTypeId.NONE;
case 1: return KeywordsInUnionTypeId.$static;
case 2: return KeywordsInUnionTypeId.internal;
default: throw StateError('Invalid value $value for bit flag enum');
}
return result;
}
static KeywordsInUnionTypeId? _createOrNull(int? value) =>
static KeywordsInUnionTypeId? _createOrNull(int? value) =>
value == null ? null : KeywordsInUnionTypeId.fromValue(value);
static const int minValue = 0;
static const int maxValue = 2;
static bool containsValue(int value) => values.containsKey(value);
static const KeywordsInUnionTypeId NONE = KeywordsInUnionTypeId._(0);
static const KeywordsInUnionTypeId $static = KeywordsInUnionTypeId._(1);
static const KeywordsInUnionTypeId internal = KeywordsInUnionTypeId._(2);
static const Map<int, KeywordsInUnionTypeId> values = {
0: NONE,
1: $static,
2: internal};
static const fb.Reader<KeywordsInUnionTypeId> reader = _KeywordsInUnionTypeIdReader();
@override
String toString() {
return 'KeywordsInUnionTypeId{value: $value}';
}
}
class _KeywordsInUnionTypeIdReader extends fb.Reader<KeywordsInUnionTypeId> {

View File

@@ -1,5 +1,5 @@
// automatically generated by the FlatBuffers compiler, do not modify
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names
library my_game.example2;

View File

@@ -1,5 +1,5 @@
// automatically generated by the FlatBuffers compiler, do not modify
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names
library my_game.example;
@@ -12,46 +12,29 @@ import './monster_test_my_game.example2_generated.dart' as my_game_example2;
import './include_test1_generated.dart';
/// Composite components of Monster color.
class Color {
enum Color {
Red(1),
Green(2),
Blue(8),
_default(0);
final int value;
const Color._(this.value);
const Color(this.value);
factory Color.fromValue(int value) {
final result = values[value];
if (result == null) {
if (value == 0) {
return Color._(0);
} else {
throw StateError('Invalid value $value for bit flag enum Color');
}
switch (value) {
case 1: return Color.Red;
case 2: return Color.Green;
case 8: return Color.Blue;
case 0: return Color._default;
default: throw StateError('Invalid value $value for bit flag enum');
}
return result;
}
static Color? _createOrNull(int? value) =>
static Color? _createOrNull(int? value) =>
value == null ? null : Color.fromValue(value);
static bool containsValue(int value) => values.containsKey(value);
static const Color Red = Color._(1);
/// \brief color Green
/// Green is bit_flag with value (1u << 1)
static const Color Green = Color._(2);
/// \brief color Blue (1u << 3)
static const Color Blue = Color._(8);
static const Map<int, Color> values = {
1: Red,
2: Green,
8: Blue};
static const fb.Reader<Color> reader = _ColorReader();
@override
String toString() {
return 'Color{value: $value}';
}
}
class _ColorReader extends fb.Reader<Color> {
@@ -65,41 +48,31 @@ class _ColorReader extends fb.Reader<Color> {
Color.fromValue(const fb.Uint8Reader().read(bc, offset));
}
class Race {
enum Race {
None(-1),
Human(0),
Dwarf(1),
Elf(2);
final int value;
const Race._(this.value);
const Race(this.value);
factory Race.fromValue(int value) {
final result = values[value];
if (result == null) {
throw StateError('Invalid value $value for bit flag enum Race');
switch (value) {
case -1: return Race.None;
case 0: return Race.Human;
case 1: return Race.Dwarf;
case 2: return Race.Elf;
default: throw StateError('Invalid value $value for bit flag enum');
}
return result;
}
static Race? _createOrNull(int? value) =>
static Race? _createOrNull(int? value) =>
value == null ? null : Race.fromValue(value);
static const int minValue = -1;
static const int maxValue = 2;
static bool containsValue(int value) => values.containsKey(value);
static const Race None = Race._(-1);
static const Race Human = Race._(0);
static const Race Dwarf = Race._(1);
static const Race Elf = Race._(2);
static const Map<int, Race> values = {
-1: None,
0: Human,
1: Dwarf,
2: Elf};
static const fb.Reader<Race> reader = _RaceReader();
@override
String toString() {
return 'Race{value: $value}';
}
}
class _RaceReader extends fb.Reader<Race> {
@@ -113,41 +86,29 @@ class _RaceReader extends fb.Reader<Race> {
Race.fromValue(const fb.Int8Reader().read(bc, offset));
}
class LongEnum {
enum LongEnum {
LongOne(2),
LongTwo(4),
LongBig(1099511627776),
_default(0);
final int value;
const LongEnum._(this.value);
const LongEnum(this.value);
factory LongEnum.fromValue(int value) {
final result = values[value];
if (result == null) {
if (value == 0) {
return LongEnum._(0);
} else {
throw StateError('Invalid value $value for bit flag enum LongEnum');
}
switch (value) {
case 2: return LongEnum.LongOne;
case 4: return LongEnum.LongTwo;
case 1099511627776: return LongEnum.LongBig;
case 0: return LongEnum._default;
default: throw StateError('Invalid value $value for bit flag enum');
}
return result;
}
static LongEnum? _createOrNull(int? value) =>
static LongEnum? _createOrNull(int? value) =>
value == null ? null : LongEnum.fromValue(value);
static bool containsValue(int value) => values.containsKey(value);
static const LongEnum LongOne = LongEnum._(2);
static const LongEnum LongTwo = LongEnum._(4);
static const LongEnum LongBig = LongEnum._(1099511627776);
static const Map<int, LongEnum> values = {
2: LongOne,
4: LongTwo,
1099511627776: LongBig};
static const fb.Reader<LongEnum> reader = _LongEnumReader();
@override
String toString() {
return 'LongEnum{value: $value}';
}
}
class _LongEnumReader extends fb.Reader<LongEnum> {
@@ -161,41 +122,31 @@ class _LongEnumReader extends fb.Reader<LongEnum> {
LongEnum.fromValue(const fb.Uint64Reader().read(bc, offset));
}
class AnyTypeId {
enum AnyTypeId {
NONE(0),
Monster(1),
TestSimpleTableWithEnum(2),
MyGame_Example2_Monster(3);
final int value;
const AnyTypeId._(this.value);
const AnyTypeId(this.value);
factory AnyTypeId.fromValue(int value) {
final result = values[value];
if (result == null) {
throw StateError('Invalid value $value for bit flag enum AnyTypeId');
switch (value) {
case 0: return AnyTypeId.NONE;
case 1: return AnyTypeId.Monster;
case 2: return AnyTypeId.TestSimpleTableWithEnum;
case 3: return AnyTypeId.MyGame_Example2_Monster;
default: throw StateError('Invalid value $value for bit flag enum');
}
return result;
}
static AnyTypeId? _createOrNull(int? value) =>
static AnyTypeId? _createOrNull(int? value) =>
value == null ? null : AnyTypeId.fromValue(value);
static const int minValue = 0;
static const int maxValue = 3;
static bool containsValue(int value) => values.containsKey(value);
static const AnyTypeId NONE = AnyTypeId._(0);
static const AnyTypeId Monster = AnyTypeId._(1);
static const AnyTypeId TestSimpleTableWithEnum = AnyTypeId._(2);
static const AnyTypeId MyGame_Example2_Monster = AnyTypeId._(3);
static const Map<int, AnyTypeId> values = {
0: NONE,
1: Monster,
2: TestSimpleTableWithEnum,
3: MyGame_Example2_Monster};
static const fb.Reader<AnyTypeId> reader = _AnyTypeIdReader();
@override
String toString() {
return 'AnyTypeId{value: $value}';
}
}
class _AnyTypeIdReader extends fb.Reader<AnyTypeId> {
@@ -209,41 +160,31 @@ class _AnyTypeIdReader extends fb.Reader<AnyTypeId> {
AnyTypeId.fromValue(const fb.Uint8Reader().read(bc, offset));
}
class AnyUniqueAliasesTypeId {
enum AnyUniqueAliasesTypeId {
NONE(0),
M(1),
TS(2),
M2(3);
final int value;
const AnyUniqueAliasesTypeId._(this.value);
const AnyUniqueAliasesTypeId(this.value);
factory AnyUniqueAliasesTypeId.fromValue(int value) {
final result = values[value];
if (result == null) {
throw StateError('Invalid value $value for bit flag enum AnyUniqueAliasesTypeId');
switch (value) {
case 0: return AnyUniqueAliasesTypeId.NONE;
case 1: return AnyUniqueAliasesTypeId.M;
case 2: return AnyUniqueAliasesTypeId.TS;
case 3: return AnyUniqueAliasesTypeId.M2;
default: throw StateError('Invalid value $value for bit flag enum');
}
return result;
}
static AnyUniqueAliasesTypeId? _createOrNull(int? value) =>
static AnyUniqueAliasesTypeId? _createOrNull(int? value) =>
value == null ? null : AnyUniqueAliasesTypeId.fromValue(value);
static const int minValue = 0;
static const int maxValue = 3;
static bool containsValue(int value) => values.containsKey(value);
static const AnyUniqueAliasesTypeId NONE = AnyUniqueAliasesTypeId._(0);
static const AnyUniqueAliasesTypeId M = AnyUniqueAliasesTypeId._(1);
static const AnyUniqueAliasesTypeId TS = AnyUniqueAliasesTypeId._(2);
static const AnyUniqueAliasesTypeId M2 = AnyUniqueAliasesTypeId._(3);
static const Map<int, AnyUniqueAliasesTypeId> values = {
0: NONE,
1: M,
2: TS,
3: M2};
static const fb.Reader<AnyUniqueAliasesTypeId> reader = _AnyUniqueAliasesTypeIdReader();
@override
String toString() {
return 'AnyUniqueAliasesTypeId{value: $value}';
}
}
class _AnyUniqueAliasesTypeIdReader extends fb.Reader<AnyUniqueAliasesTypeId> {
@@ -257,41 +198,31 @@ class _AnyUniqueAliasesTypeIdReader extends fb.Reader<AnyUniqueAliasesTypeId> {
AnyUniqueAliasesTypeId.fromValue(const fb.Uint8Reader().read(bc, offset));
}
class AnyAmbiguousAliasesTypeId {
enum AnyAmbiguousAliasesTypeId {
NONE(0),
M1(1),
M2(2),
M3(3);
final int value;
const AnyAmbiguousAliasesTypeId._(this.value);
const AnyAmbiguousAliasesTypeId(this.value);
factory AnyAmbiguousAliasesTypeId.fromValue(int value) {
final result = values[value];
if (result == null) {
throw StateError('Invalid value $value for bit flag enum AnyAmbiguousAliasesTypeId');
switch (value) {
case 0: return AnyAmbiguousAliasesTypeId.NONE;
case 1: return AnyAmbiguousAliasesTypeId.M1;
case 2: return AnyAmbiguousAliasesTypeId.M2;
case 3: return AnyAmbiguousAliasesTypeId.M3;
default: throw StateError('Invalid value $value for bit flag enum');
}
return result;
}
static AnyAmbiguousAliasesTypeId? _createOrNull(int? value) =>
static AnyAmbiguousAliasesTypeId? _createOrNull(int? value) =>
value == null ? null : AnyAmbiguousAliasesTypeId.fromValue(value);
static const int minValue = 0;
static const int maxValue = 3;
static bool containsValue(int value) => values.containsKey(value);
static const AnyAmbiguousAliasesTypeId NONE = AnyAmbiguousAliasesTypeId._(0);
static const AnyAmbiguousAliasesTypeId M1 = AnyAmbiguousAliasesTypeId._(1);
static const AnyAmbiguousAliasesTypeId M2 = AnyAmbiguousAliasesTypeId._(2);
static const AnyAmbiguousAliasesTypeId M3 = AnyAmbiguousAliasesTypeId._(3);
static const Map<int, AnyAmbiguousAliasesTypeId> values = {
0: NONE,
1: M1,
2: M2,
3: M3};
static const fb.Reader<AnyAmbiguousAliasesTypeId> reader = _AnyAmbiguousAliasesTypeIdReader();
@override
String toString() {
return 'AnyAmbiguousAliasesTypeId{value: $value}';
}
}
class _AnyAmbiguousAliasesTypeIdReader extends fb.Reader<AnyAmbiguousAliasesTypeId> {
@@ -1461,7 +1392,7 @@ class MonsterT implements fb.Packable {
this.testrequirednestedflatbuffer,
this.scalarKeySortedTables,
this.nativeInline,
this.longEnumNonEnumDefault = const LongEnum._(0),
this.longEnumNonEnumDefault = LongEnum._default,
this.longEnumNormalDefault = LongEnum.LongOne,
this.nanDefault = double.nan,
this.infDefault = double.infinity,

View File

@@ -1,5 +1,5 @@
// automatically generated by the FlatBuffers compiler, do not modify
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names
library my_game;

24
docs/README.md Normal file
View File

@@ -0,0 +1,24 @@
# Documentation
This is the source of the FlatBuffers documentation, that is served at
https://flatbuffers.dev.
## Local Building
The documentation can be built and served locally during development, see [https//flatbuffers.dev/contributing/#local-development] for full details.
__tl;dr__
Install:
```
pip install mkdocs-material
pip install mkdocs-redirects
```
Build and Serve:
```
mkdocs serve -f docs/mkdocs.yml
```

View File

@@ -1,14 +0,0 @@
<!-- Google Analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-49880327-7', 'auto');
ga('send', 'pageview');
</script>
</body>
</html>

View File

@@ -1,62 +0,0 @@
<!-- HTML header for doxygen 1.8.6-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen $doxygenversion"/>
<!--BEGIN PROJECT_NAME--><title>$projectname: $title</title><!--END PROJECT_NAME-->
<!--BEGIN !PROJECT_NAME--><title>$title</title><!--END !PROJECT_NAME-->
<link href="$relpath^tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="$relpath^jquery.js"></script>
<script type="text/javascript" src="$relpath^dynsections.js"></script>
$treeview
$search
$mathjax
<link href="$relpath^$stylesheet" rel="stylesheet" type="text/css" />
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,400italic,500,500italic,700,700italic|Roboto+Mono:400,700" rel="stylesheet">
$extrastylesheet
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<!--BEGIN TITLEAREA-->
<div id="titlearea" style="height: 110px;">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<!--BEGIN PROJECT_LOGO-->
<td id="projectlogo"><img alt="Logo" src="$relpath^$projectlogo"/></td>
<!--END PROJECT_LOGO-->
<td id="commonprojectlogo">
<img alt="Logo" src="$relpath^fpl_logo_small.png"/>
</td>
<!--BEGIN PROJECT_NAME-->
<td style="padding-left: 0.5em;">
<div id="projectname">$projectname
<!--BEGIN PROJECT_NUMBER-->&#160;<span id="projectnumber">$projectnumber</span><!--END PROJECT_NUMBER-->
</div>
<div style="font-size:12px;">
An open source project by <a href="https://developers.google.com/games/#Tools">FPL</a>.
</div>
<!--BEGIN PROJECT_BRIEF--><div id="projectbrief">$projectbrief</div><!--END PROJECT_BRIEF-->
</td>
<!--END PROJECT_NAME-->
<!--BEGIN !PROJECT_NAME-->
<!--BEGIN PROJECT_BRIEF-->
<td style="padding-left: 0.5em;">
<div id="projectbrief">$projectbrief</div>
</td>
<!--END PROJECT_BRIEF-->
<!--END !PROJECT_NAME-->
<!--BEGIN DISABLE_INDEX-->
<!--BEGIN SEARCHENGINE-->
<td>$searchbox</td>
<!--END SEARCHENGINE-->
<!--END DISABLE_INDEX-->
</tr>
</tbody>
</table>
</div>
<!--END TITLEAREA-->
<!-- end header part -->

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 KiB

159
docs/mkdocs.yml Normal file
View File

@@ -0,0 +1,159 @@
site_name: FlatBuffers Docs
docs_dir: source
site_url: https://flatbuffers.dev
repo_name: google/FlatBuffers
repo_url: https://github.com/google/flatbuffers
edit_uri: edit/master/docs/source/
copyright: Copyright &copy; 2025 Google
theme:
name: material
logo: assets/flatbuffers_logo.svg
icon:
repo: fontawesome/brands/github
custom_dir: overrides
palette:
# Palette toggle for light mode
- scheme: default
toggle:
icon: material/brightness-7
name: Switch to dark mode
# Palette toggle for dark mode
- scheme: slate
toggle:
icon: material/brightness-4
name: Switch to light mode
features:
# Allows code block annotations
- content.code.annotate
# Allows content tabs to link together
- content.tabs.link
# Expand nav folders by default
- navigation.expand
# Enable the footer
- navigation.footer
# Auto hide the header after scrolling
- header.autohide
- content.action.edit
extra:
social:
- icon: fontawesome/brands/github
link: https://github.com/google/flatbuffers
- icon: fontawesome/brands/discord
link: https:///discord.gg/6qgKs3R
- icon: fontawesome/brands/x-twitter
link: https://twitter.com/dbaileychess
plugins:
# Use redirects to update links from the original docs to the new ones.
#
# https://github.com/mkdocs/mkdocs-redirects
- redirects:
# Note the .html are suffixed with .md to avoid warnings. Got from
# https://github.com/mkdocs/mkdocs-redirects/issues/51#issuecomment-2408548029
redirect_maps:
'flatbuffers_guide_building.html.md': 'building.md'
'flatbuffers_guide_tutorial.html.md': 'tutorial.md'
'flatbuffers_guide_using_schema_compiler.html.md': 'flatc.md'
'flatbuffers_guide_writing_schema.html.md': 'schema.md'
'md__schemas.html.md': 'schema.md' # issue #8485
'flatbuffers_guide_use_c.html.md': 'languages/c.md'
'flatbuffers_guide_use_cpp.html.md': 'languages/cpp.md'
'flatbuffers_guide_use_c-sharp.html.md': 'languages/c_sharp.md'
'flatbuffers_guide_use_dart.html.md': 'languages/dart.md'
'flatbuffers_guide_use_go.html.md': 'languages/go.md'
'flatbuffers_guide_use_java.html.md': 'languages/java.md'
'flatbuffers_guide_use_javascript.html.md': 'languages/javascript.md'
'flatbuffers_guide_use_lobster.html.md': 'languages/lobster.md'
'flatbuffers_guide_use_lua.html.md': 'languages/lua.md'
'flatbuffers_guide_use_php.html.md': 'languages/php.md'
'flatbuffers_guide_use_python.html.md': 'languages/python.md'
'flatbuffers_guide_use_rust.html.md': 'languages/rust.md'
'flatbuffers_guide_use_swift.html.md': 'languages/swift.md'
'flatbuffers_guide_use_typescript.html.md': 'languages/typescript.md'
'flatbuffers_grpc_guide_use_cpp.html.md' : "languages/cpp.md#grpc"
'flatbuffers_support.html.md': 'support.md'
'flatbuffers_white_paper.html.md': 'white_paper.md'
'flatbuffers_grammar.html.md': 'grammar.md'
'flatbuffers_internals.html.md': 'internals.md'
'intermediate_representation.html.md': 'intermediate_representation.md'
'flatbuffers_benchmarks.html.md': 'benchmarks.md'
'flexbuffers.html.md': 'flexbuffers.md'
'contributing.html.md': 'contributing.md'
markdown_extensions:
- admonition
- attr_list
- md_in_html
- pymdownx.critic
- pymdownx.details
- pymdownx.emoji:
emoji_index: !!python/name:material.extensions.emoji.twemoji
emoji_generator: !!python/name:material.extensions.emoji.to_svg
- pymdownx.snippets:
# Allows direct embedded of remote files
url_download: true
- pymdownx.superfences
- pymdownx.tabbed:
alternate_style: true
slugify: !!python/object/apply:pymdownx.slugs.slugify
kwds:
case: lower
- pymdownx.highlight:
extend_pygments_lang:
# PHP wasn't highlighting correctly. This is a work around found
# https://github.com/squidfunk/mkdocs-material/issues/138#issuecomment-2294025627
- name: php
lang: php
options:
startinline: true
- tables
nav:
- Overview: "index.md"
- Quick Start: "quick_start.md"
- Tutorial: "tutorial.md"
- Compiler (flatc):
- Building: "building.md"
- Using: "flatc.md"
- Schema (.fbs):
- Overview: "schema.md"
- Evolution: "evolution.md"
- Grammar: "grammar.md"
- Language Guides:
- C: "languages/c.md"
- C++: "languages/cpp.md"
- C#: "languages/c_sharp.md"
- Dart: "languages/dart.md"
- Go: "languages/go.md"
- Java: "languages/java.md"
- JavasScript: "languages/javascript.md"
- Kotlin: "languages/kotlin.md"
- Lobster: "languages/lobster.md"
- Lua: "languages/lua.md"
- PHP: "languages/php.md"
- Python: "languages/python.md"
- Rust: "languages/rust.md"
- Swift: "languages/swift.md"
- TypeScript: "languages/typescript.md"
- Supported Configurations: "support.md"
- White Paper: "white_paper.md"
- Advanced:
- FlatBuffers Internals: "internals.md"
- Intermediate Representation: "intermediate_representation.md"
- Annotating Buffers (.afb): "annotation.md"
- Benchmarks: "benchmarks.md"
- FlexBuffers (Schema-less version): "flexbuffers.md"
- Contributing: "contributing.md"

10
docs/overrides/404.html Normal file
View File

@@ -0,0 +1,10 @@
{% extends "main.html" %}
<!-- Content -->
{% block content %}
<h1>404 - Not found</h1>
<br>
FlatBuffers has migrated their documentation system recently.
Please <a href="https://github.com/google/flatbuffers/issues/new?template=404-doc.md">file an issue</a> indicating the broken link.
{% endblock %}

1
docs/overrides/main.html Normal file
View File

@@ -0,0 +1 @@
{% extends "base.html" %}

1
docs/source/CNAME Normal file
View File

@@ -0,0 +1 @@
flatbuffers.dev

View File

@@ -1 +0,0 @@
../../CONTRIBUTING.md

View File

@@ -1,188 +0,0 @@
FlatBuffers {#flatbuffers_index}
===========
# Overview {#flatbuffers_overview}
[FlatBuffers](@ref flatbuffers_overview) is an efficient cross platform
serialization library for C++, C#, C, Go, Java, Kotlin, JavaScript, Lobster, Lua, TypeScript, PHP, Python, Rust and Swift.
It was originally created at Google for game development and other
performance-critical applications.
It is available as Open Source on [GitHub](http://github.com/google/flatbuffers)
under the Apache license, v2 (see LICENSE).
## Why use FlatBuffers?
- **Access to serialized data without parsing/unpacking** - What sets
FlatBuffers apart is that it represents hierarchical data in a flat
binary buffer in such a way that it can still be accessed directly
without parsing/unpacking, while also still supporting data
structure evolution (forwards/backwards compatibility).
- **Memory efficiency and speed** - The only memory needed to access
your data is that of the buffer. It requires 0 additional allocations
(in C++, other languages may vary). FlatBuffers is also very
suitable for use with mmap (or streaming), requiring only part of the
buffer to be in memory. Access is close to the speed of raw
struct access with only one extra indirection (a kind of vtable) to
allow for format evolution and optional fields. It is aimed at
projects where spending time and space (many memory allocations) to
be able to access or construct serialized data is undesirable, such
as in games or any other performance sensitive applications. See the
[benchmarks](@ref flatbuffers_benchmarks) for details.
- **Flexible** - Optional fields means not only do you get great
forwards and backwards compatibility (increasingly important for
long-lived games: don't have to update all data with each new
version!). It also means you have a lot of choice in what data you
write and what data you don't, and how you design data structures.
- **Tiny code footprint** - Small amounts of generated code, and just
a single small header as the minimum dependency, which is very easy
to integrate. Again, see the benchmark section for details.
- **Strongly typed** - Errors happen at compile time rather than
manually having to write repetitive and error prone run-time checks.
Useful code can be generated for you.
- **Convenient to use** - Generated C++ code allows for terse access
& construction code. Then there's optional functionality for parsing
schemas and JSON-like text representations at runtime efficiently if
needed (faster and more memory efficient than other JSON
parsers).
Java, Kotlin and Go code supports object-reuse. C# has efficient struct based
accessors.
- **Cross platform code with no dependencies** - C++ code will work
with any recent gcc/clang and VS2010. Comes with build files for the tests &
samples (Android .mk files, and cmake for all other platforms).
### Why not use Protocol Buffers, or .. ?
Protocol Buffers is indeed relatively similar to FlatBuffers,
with the primary difference being that FlatBuffers does not need a parsing/
unpacking step to a secondary representation before you can
access data, often coupled with per-object memory allocation. The code
is an order of magnitude bigger, too. Protocol Buffers has no optional
text import/export.
### But all the cool kids use JSON!
JSON is very readable (which is why we use it as our optional text
format) and very convenient when used together with dynamically typed
languages (such as JavaScript). When serializing data from statically
typed languages, however, JSON not only has the obvious drawback of runtime
inefficiency, but also forces you to write *more* code to access data
(counterintuitively) due to its dynamic-typing serialization system.
In this context, it is only a better choice for systems that have very
little to no information ahead of time about what data needs to be stored.
If you do need to store data that doesn't fit a schema, FlatBuffers also
offers a schema-less (self-describing) version!
Read more about the "why" of FlatBuffers in the
[white paper](@ref flatbuffers_white_paper).
### Who uses FlatBuffers?
- [Cocos2d-x](http://www.cocos2d-x.org/), the #1 open source mobile game
engine, uses it to serialize all their
[game data](http://www.cocos2d-x.org/reference/native-cpp/V3.5/d7/d2d/namespaceflatbuffers.html).
- [Facebook](http://facebook.com/) uses it for client-server communication in
their Android app. They have a nice
[article](https://code.facebook.com/posts/872547912839369/improving-facebook-s-performance-on-android-with-flatbuffers/)
explaining how it speeds up loading their posts.
- [Fun Propulsion Labs](https://developers.google.com/games/#Tools)
at Google uses it extensively in all their libraries and games.
## Usage in brief
This section is a quick rundown of how to use this system. Subsequent
sections provide a more in-depth usage guide.
- Write a schema file that allows you to define the data structures
you may want to serialize. Fields can have a scalar type
(ints/floats of all sizes), or they can be a: string; array of any type;
reference to yet another object; or, a set of possible objects (unions).
Fields are optional and have defaults, so they don't need to be
present for every object instance.
- Use `flatc` (the FlatBuffer compiler) to generate a C++ header (or
Java/Kotlin/C#/Go/Python.. classes) with helper classes to access and construct
serialized data. This header (say `mydata_generated.h`) only depends on
`flatbuffers.h`, which defines the core functionality.
- Use the `FlatBufferBuilder` class to construct a flat binary buffer.
The generated functions allow you to add objects to this
buffer recursively, often as simply as making a single function call.
- Store or send your buffer somewhere!
- When reading it back, you can obtain the pointer to the root object
from the binary buffer, and from there traverse it conveniently
in-place with `object->field()`.
## In-depth documentation
- How to [build the compiler](@ref flatbuffers_guide_building) and samples on
various platforms.
- How to [use the compiler](@ref flatbuffers_guide_using_schema_compiler).
- How to [write a schema](@ref flatbuffers_guide_writing_schema).
- How to [use the generated C++ code](@ref flatbuffers_guide_use_cpp) in your
own programs.
- How to [use the generated Java code](@ref flatbuffers_guide_use_java)
in your own programs.
- How to [use the generated C# code](@ref flatbuffers_guide_use_c-sharp)
in your own programs.
- How to [use the generated Kotlin code](@ref flatbuffers_guide_use_kotlin)
in your own programs.
- How to [use the generated Go code](@ref flatbuffers_guide_use_go) in your
own programs.
- How to [use the generated Lua code](@ref flatbuffers_guide_use_lua) in your
own programs.
- How to [use the generated JavaScript code](@ref flatbuffers_guide_use_javascript) in your
own programs.
- How to [use the generated TypeScript code](@ref flatbuffers_guide_use_typescript) in your
own programs.
- How to [use FlatBuffers in C with `flatcc`](@ref flatbuffers_guide_use_c) in your
own programs.
- How to [use the generated Lobster code](@ref flatbuffers_guide_use_lobster) in your
own programs.
- How to [use the generated Rust code](@ref flatbuffers_guide_use_rust) in your
own programs.
- How to [use the generated Swift code](@ref flatbuffers_guide_use_swift) in your
own programs.
- [Support matrix](@ref flatbuffers_support) for platforms/languages/features.
- Some [benchmarks](@ref flatbuffers_benchmarks) showing the advantage of
using FlatBuffers.
- A [white paper](@ref flatbuffers_white_paper) explaining the "why" of
FlatBuffers.
- How to use the [schema-less](@ref flexbuffers) version of
FlatBuffers.
- A description of the [internals](@ref flatbuffers_internals) of FlatBuffers.
- A formal [grammar](@ref flatbuffers_grammar) of the schema language.
## Online resources
- [GitHub repository](http://github.com/google/flatbuffers)
- [Landing page](http://google.github.io/flatbuffers)
- [FlatBuffers Google Group](https://groups.google.com/forum/#!forum/flatbuffers)
- [Discord](https://discord.gg/6qgKs3R) and [Gitter](https://gitter.im/lobster_programming_language/community) chat.
- [FlatBuffers Issues Tracker](http://github.com/google/flatbuffers/issues)
- Independent implementations & tools:
- [FlatCC](https://github.com/dvidelabs/flatcc) Alternative FlatBuffers
parser, code generator and runtime all in C.
- Videos:
- Colt's [DevByte](https://www.youtube.com/watch?v=iQTxMkSJ1dQ).
- GDC 2015 [Lightning Talk](https://www.youtube.com/watch?v=olmL1fUnQAQ).
- FlatBuffers for [Go](https://www.youtube.com/watch?v=-BPVId_lA5w).
- Evolution of FlatBuffers
[visualization](https://www.youtube.com/watch?v=a0QE0xS8rKM).
- Useful documentation created by others:
- [FlatBuffers in Go](https://rwinslow.com/tags/flatbuffers/)
- [FlatBuffers in Android](http://frogermcs.github.io/flatbuffers-in-android-introdution/)
- [Parsing JSON to FlatBuffers in Java](http://frogermcs.github.io/json-parsing-with-flatbuffers-in-android/)
- [FlatBuffers in Unity](http://exiin.com/blog/flatbuffers-for-unity-sample-code/)
- [FlexBuffers C#](https://github.com/mzaks/FlexBuffers-CSharp) and
[article](https://medium.com/@icex33/flexbuffers-for-unity3d-4d1ab5c53fbe?)
on its use.

View File

@@ -1,26 +0,0 @@
Go API
======
\addtogroup flatbuffers_go_api
<!-- Note: The `GoApi_generate.txt` code snippet was generated using `godoc` and
customized for use with this markdown file. To regenerate the file, use the
`godoc` tool (http://godoc.org) with the files in the `flatbuffers/go`
folder.
You may need to ensure that copies of the files exist in the `src/`
subfolder at the path set by the `$GOROOT` environment variable. You can
either move the files to `$GOROOT/src/flatbuffers` manually, if `$GOROOT`
is already set, otherwise you will need to manually set the `$GOROOT`
variable to a path and create `src/flatbuffers` subfolders at that path.
Then copy the flatbuffers files into `$GOROOT/src/flatbuffers`. (Some
versions of `godoc` include a `-path` flag. This could be used instead, if
available).
Once the files exist at the `$GOROOT/src/flatbuffers` location, you can
regenerate this doc using the following command:
`godoc flatbuffers > GoApi_generated.txt`.
After the documentation is generated, you will have to manually remove any
non-user facing documentation from this file. -->
\snippet GoApi_generated.txt Go API

View File

@@ -1,125 +0,0 @@
// This file was generated using `godoc` and customized for use with the
// API Reference documentation. To recreate this file, use the `godoc` tool
// (http://godoc.org) with the files in the `flatbuffers/go` folder.
//
// Note: You may need to ensure that copies of the files exist in the
// `src/` subfolder at the path set by the `$GOROOT` environment variable.
// You can either move the files to `$GOROOT/src/flatbuffers` manually, if
// `$GOROOT` is already set, otherwise you will need to manually set the
// `$GOROOT` variable to a path and create `src/flatbuffers` subfolders at that
// path. Then copy these files into `$GOROOT/src/flatbuffers`. (Some versions of
// `godoc` include a `-path` flag. This could be used instead, if available).
//
// Once the files exist at the `$GOROOT/src/flatbuffers` location, you can
// regenerate this doc using the following command:
// `godoc flatbuffers > GoApi_generated.txt`.
//
// After the documentation is generated, you will have to manually remove any
// non-user facing documentation from this file.
/// [Go API]
PACKAGE DOCUMENTATION
package flatbuffers
Package flatbuffers provides facilities to read and write flatbuffers
objects.
TYPES
type Builder struct {
// `Bytes` gives raw access to the buffer. Most users will want to use
// FinishedBytes() instead.
Bytes []byte
}
Builder is a state machine for creating FlatBuffer objects. Use a
Builder to construct object(s) starting from leaf nodes.
A Builder constructs byte buffers in a last-first manner for simplicity
and performance.
FUNCTIONS
func NewBuilder(initialSize int) *Builder
NewBuilder initializes a Builder of size `initial_size`. The internal
buffer is grown as needed.
func (b *Builder) CreateByteString(s []byte) UOffsetT
CreateByteString writes a byte slice as a string (null-terminated).
func (b *Builder) CreateByteVector(v []byte) UOffsetT
CreateByteVector writes a ubyte vector
func (b *Builder) CreateString(s string) UOffsetT
CreateString writes a null-terminated string as a vector.
func (b *Builder) EndVector(vectorNumElems int) UOffsetT
EndVector writes data necessary to finish vector construction.
func (b *Builder) Finish(rootTable UOffsetT)
Finish finalizes a buffer, pointing to the given `rootTable`.
func (b *Builder) FinishedBytes() []byte
FinishedBytes returns a pointer to the written data in the byte buffer.
Panics if the builder is not in a finished state (which is caused by
calling `Finish()`).
func (b *Builder) Head() UOffsetT
Head gives the start of useful data in the underlying byte buffer. Note:
unlike other functions, this value is interpreted as from the left.
func (b *Builder) PrependBool(x bool)
PrependBool prepends a bool to the Builder buffer. Aligns and checks for
space.
func (b *Builder) PrependByte(x byte)
PrependByte prepends a byte to the Builder buffer. Aligns and checks for
space.
func (b *Builder) PrependFloat32(x float32)
PrependFloat32 prepends a float32 to the Builder buffer. Aligns and
checks for space.
func (b *Builder) PrependFloat64(x float64)
PrependFloat64 prepends a float64 to the Builder buffer. Aligns and
checks for space.
func (b *Builder) PrependInt16(x int16)
PrependInt16 prepends a int16 to the Builder buffer. Aligns and checks
for space.
func (b *Builder) PrependInt32(x int32)
PrependInt32 prepends a int32 to the Builder buffer. Aligns and checks
for space.
func (b *Builder) PrependInt64(x int64)
PrependInt64 prepends a int64 to the Builder buffer. Aligns and checks
for space.
func (b *Builder) PrependInt8(x int8)
PrependInt8 prepends a int8 to the Builder buffer. Aligns and checks for
space.
func (b *Builder) PrependUOffsetT(off UOffsetT)
PrependUOffsetT prepends an UOffsetT, relative to where it will be
written.
func (b *Builder) PrependUint16(x uint16)
PrependUint16 prepends a uint16 to the Builder buffer. Aligns and checks
for space.
func (b *Builder) PrependUint32(x uint32)
PrependUint32 prepends a uint32 to the Builder buffer. Aligns and checks
for space.
func (b *Builder) PrependUint64(x uint64)
PrependUint64 prepends a uint64 to the Builder buffer. Aligns and checks
for space.
func (b *Builder) PrependUint8(x uint8)
PrependUint8 prepends a uint8 to the Builder buffer. Aligns and checks
for space.
func (b *Builder) Reset()
Reset truncates the underlying Builder buffer, facilitating alloc-free
reuse of a Builder. It also resets bookkeeping data.
/// [Go API]

View File

@@ -1,74 +0,0 @@
Grammar of the schema language {#flatbuffers_grammar}
==============================
schema = include*
( namespace\_decl | type\_decl | enum\_decl | root\_decl |
file_extension_decl | file_identifier_decl |
attribute\_decl | rpc\_decl | object )*
include = `include` string\_constant `;`
namespace\_decl = `namespace` ident ( `.` ident )* `;`
attribute\_decl = `attribute` ident | `"` ident `"` `;`
type\_decl = ( `table` | `struct` ) ident metadata `{` field\_decl+ `}`
enum\_decl = ( `enum` ident `:` type | `union` ident ) metadata `{`
commasep( enumval\_decl ) `}`
root\_decl = `root_type` ident `;`
field\_decl = ident `:` type [ `=` scalar ] metadata `;`
rpc\_decl = `rpc_service` ident `{` rpc\_method+ `}`
rpc\_method = ident `(` ident `)` `:` ident metadata `;`
type = `bool` | `byte` | `ubyte` | `short` | `ushort` | `int` | `uint` |
`float` | `long` | `ulong` | `double` |
`int8` | `uint8` | `int16` | `uint16` | `int32` | `uint32`| `int64` | `uint64` |
`float32` | `float64` |
`string` | `[` type `]` | ident
enumval\_decl = ident [ `=` integer\_constant ] metadata
metadata = [ `(` commasep( ident [ `:` single\_value ] ) `)` ]
scalar = boolean\_constant | integer\_constant | float\_constant
object = `{` commasep( ident `:` value ) `}`
single\_value = scalar | string\_constant
value = single\_value | object | `[` commasep( value ) `]`
commasep(x) = [ x ( `,` x )\* ]
file_extension_decl = `file_extension` string\_constant `;`
file_identifier_decl = `file_identifier` string\_constant `;`
string\_constant = `\".*?\"`
ident = `[a-zA-Z_][a-zA-Z0-9_]*`
`[:digit:]` = `[0-9]`
`[:xdigit:]` = `[0-9a-fA-F]`
dec\_integer\_constant = `[-+]?[:digit:]+`
hex\_integer\_constant = `[-+]?0[xX][:xdigit:]+`
integer\_constant = dec\_integer\_constant | hex\_integer\_constant
dec\_float\_constant = `[-+]?(([.][:digit:]+)|([:digit:]+[.][:digit:]*)|([:digit:]+))([eE][-+]?[:digit:]+)?`
hex\_float\_constant = `[-+]?0[xX](([.][:xdigit:]+)|([:xdigit:]+[.][:xdigit:]*)|([:xdigit:]+))([pP][-+]?[:digit:]+)`
special\_float\_constant = `[-+]?(nan|inf|infinity)`
float\_constant = dec\_float\_constant | hex\_float\_constant | special\_float\_constant
boolean\_constant = `true` | `false`

View File

@@ -1,32 +0,0 @@
## Prerequisites
To generate the docs for FlatBuffers from the source files, you
will first need to install two programs.
1. You will need to install `doxygen`. See
[Download Doxygen](https://doxygen.nl/download.html).
2. You will need to install `doxypypy` to format python comments appropriately.
Install it from [here](https://github.com/Feneric/doxypypy).
*Note: You will need both `doxygen` and `doxypypy` to be in your
[PATH](https://en.wikipedia.org/wiki/PATH_(variable)) environment variable.*
After you have both of those files installed and in your path, you need to
set up the `py_filter` to invoke `doxypypy` from `doxygen`.
Follow the steps
[here](https://github.com/Feneric/doxypypy#invoking-doxypypy-from-doxygen).
## Generating Docs
Run the following commands to generate the docs:
`cd flatbuffers/docs/source`
`doxygen`
The output is placed in `flatbuffers/docs/html`.
*Note: The Go API Reference code must be generated ahead of time. For
instructions on how to regenerated this file, please read the comments
in `GoApi.md`.*

View File

@@ -1,685 +0,0 @@
Writing a schema {#flatbuffers_guide_writing_schema}
================
The syntax of the schema language (aka IDL, [Interface Definition Language][])
should look quite familiar to users of any of the C family of
languages, and also to users of other IDLs. Let's look at an example
first:
// example IDL file
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;
}
root_type Monster;
(`Weapon` & `Pickup` not defined as part of this example).
### Tables
Tables are the main way of defining objects in FlatBuffers, and consist of a
name (here `Monster`) and a list of fields. Each field has a name, a type, and
optionally a default value. If the default value is not specified in the schema,
it will be `0` for scalar types, or `null` for other types. Some languages
support setting a scalar's default to `null`. This makes the scalar optional.
Fields do not have to appear in the wire representation, and you can choose
to omit fields when constructing an object. You have the flexibility to add
fields without fear of bloating your data. This design is also FlatBuffer's
mechanism for forward and backwards compatibility. Note that:
- You can add new fields in the schema ONLY at the end of a table
definition. Older data will still
read correctly, and give you the default value when read. Older code
will simply ignore the new field.
If you want to have flexibility to use any order for fields in your
schema, you can manually assign ids (much like Protocol Buffers),
see the `id` attribute below.
- You cannot delete fields you don't use anymore from the schema,
but you can simply
stop writing them into your data for almost the same effect.
Additionally you can mark them as `deprecated` as in the example
above, which will prevent the generation of accessors in the
generated C++, as a way to enforce the field not being used any more.
(careful: this may break code!).
- You may change field names and table names, if you're ok with your
code breaking until you've renamed them there too.
See "Schema evolution examples" below for more on this
topic.
### Structs
Similar to a table, only now none of the fields are optional (so no defaults
either), and fields may not be added or be deprecated. Structs may only contain
scalars or other structs. Use this for
simple objects where you are very sure no changes will ever be made
(as quite clear in the example `Vec3`). Structs use less memory than
tables and are even faster to access (they are always stored in-line in their
parent object, and use no virtual table).
### Types
Built-in scalar types are
- 8 bit: `byte` (`int8`), `ubyte` (`uint8`), `bool`
- 16 bit: `short` (`int16`), `ushort` (`uint16`)
- 32 bit: `int` (`int32`), `uint` (`uint32`), `float` (`float32`)
- 64 bit: `long` (`int64`), `ulong` (`uint64`), `double` (`float64`)
The type names in parentheses are alias names such that for example
`uint8` can be used in place of `ubyte`, and `int32` can be used in
place of `int` without affecting code generation.
Built-in non-scalar types:
- Vector of any other type (denoted with `[type]`). Nesting vectors
is not supported, instead you can wrap the inner vector in a table.
- `string`, which may only hold UTF-8 or 7-bit ASCII. For other text encodings
or general binary data use vectors (`[byte]` or `[ubyte]`) instead.
- References to other tables or structs, enums or unions (see
below).
You can't change types of fields once they're used, with the exception
of same-size data where a `reinterpret_cast` would give you a desirable result,
e.g. you could change a `uint` to an `int` if no values in current data use the
high bit yet.
### Arrays
Arrays are a convenience short-hand for a fixed-length collection of elements.
Arrays can be used to replace the following schema:
struct Vec3 {
x:float;
y:float;
z:float;
}
with the following schema:
struct Vec3 {
v:[float:3];
}
Both representations are binary equivalent.
Arrays are currently only supported in a `struct`.
### Default, Optional and Required Values
There are three, mutually exclusive, reactions to the non-presence of a table's
field in the binary data:
1. Default valued fields will return the default value (as defined in the schema).
2. Optional valued fields will return some form of `null` depending on the
local language. (In a sense, `null` is the default value).
3. Required fields will cause an error. Flatbuffer verifiers would
consider the whole buffer invalid. See the `required` tag below.
When writing a schema, values are a sequence of digits. Values may be optionally
followed by a decimal point (`.`) and more digits, for float constants, or
optionally prefixed by a `-`. Floats may also be in scientific notation;
optionally ending with an `e` or `E`, followed by a `+` or `-` and more digits.
Values can also be the keyword `null`.
Only scalar values can have defaults, non-scalar (string/vector/table) fields
default to `null` when not present.
You generally do not want to change default values after they're initially
defined. Fields that have the default value are not actually stored in the
serialized data (see also Gotchas below). Values explicitly written by code
generated by the old schema old version, if they happen to be the default, will
be read as a different value by code generated with the new schema. This is
slightly less bad when converting an optional scalar into a default valued
scalar since non-presence would not be overloaded with a previous default value.
There are situations, however, where this may be desirable, especially if you
can ensure a simultaneous rebuild of all code.
### Enums
Define a sequence of named constants, each with a given value, or
increasing by one from the previous one. The default first value
is `0`. As you can see in the enum declaration, you specify the underlying
integral type of the enum with `:` (in this case `byte`), which then determines
the type of any fields declared with this enum type.
Only integer types are allowed, i.e. `byte`, `ubyte`, `short` `ushort`, `int`,
`uint`, `long` and `ulong`.
Typically, enum values should only ever be added, never removed (there is no
deprecation for enums). This requires code to handle forwards compatibility
itself, by handling unknown enum values.
### Unions
Unions share a lot of properties with enums, but instead of new names
for constants, you use names of tables. You can then declare
a union field, which can hold a reference to any of those types, and
additionally a field with the suffix `_type` is generated that holds
the corresponding enum value, allowing you to know which type to cast
to at runtime.
It's possible to give an alias name to a type union. This way a type can even be
used to mean different things depending on the name used:
table PointPosition { x:uint; y:uint; }
table MarkerPosition {}
union Position {
Start:MarkerPosition,
Point:PointPosition,
Finish:MarkerPosition
}
Unions contain a special `NONE` marker to denote that no value is stored so that
name cannot be used as an alias.
Unions are a good way to be able to send multiple message types as a FlatBuffer.
Note that because a union field is really two fields, it must always be
part of a table, it cannot be the root of a FlatBuffer by itself.
If you have a need to distinguish between different FlatBuffers in a more
open-ended way, for example for use as files, see the file identification
feature below.
There is an experimental support only in C++ for a vector of unions (and
types). In the example IDL file above, use [Any] to add a vector of Any to
Monster table. There is also experimental support for other types besides
tables in unions, in particular structs and strings. There's no direct support
for scalars in unions, but they can be wrapped in a struct at no space cost.
### Namespaces
These will generate the corresponding namespace in C++ for all helper
code, and packages in Java. You can use `.` to specify nested namespaces /
packages.
### Includes
You can include other schemas files in your current one, e.g.:
include "mydefinitions.fbs";
This makes it easier to refer to types defined elsewhere. `include`
automatically ensures each file is parsed just once, even when referred to
more than once.
When using the `flatc` compiler to generate code for schema definitions,
only definitions in the current file will be generated, not those from the
included files (those you still generate separately).
### Root type
This declares what you consider to be the root table of the serialized
data. This is particularly important for parsing JSON data, which doesn't
include object type information.
### File identification and extension
Typically, a FlatBuffer binary buffer is not self-describing, i.e. it
needs you to know its schema to parse it correctly. But if you
want to use a FlatBuffer as a file format, it would be convenient
to be able to have a "magic number" in there, like most file formats
have, to be able to do a sanity check to see if you're reading the
kind of file you're expecting.
Now, you can always prefix a FlatBuffer with your own file header,
but FlatBuffers has a built-in way to add an identifier to a
FlatBuffer that takes up minimal space, and keeps the buffer
compatible with buffers that don't have such an identifier.
You can specify in a schema, similar to `root_type`, that you intend
for this type of FlatBuffer to be used as a file format:
file_identifier "MYFI";
Identifiers must always be exactly 4 characters long. These 4 characters
will end up as bytes at offsets 4-7 (inclusive) in the buffer.
For any schema that has such an identifier, `flatc` will automatically
add the identifier to any binaries it generates (with `-b`),
and generated calls like `FinishMonsterBuffer` also add the identifier.
If you have specified an identifier and wish to generate a buffer
without one, you can always still do so by calling
`FlatBufferBuilder::Finish` explicitly.
After loading a buffer, you can use a call like
`MonsterBufferHasIdentifier` to check if the identifier is present.
Note that this is best for open-ended uses such as files. If you simply wanted
to send one of a set of possible messages over a network for example, you'd
be better off with a union.
Additionally, by default `flatc` will output binary files as `.bin`.
This declaration in the schema will change that to whatever you want:
file_extension "ext";
### RPC interface declarations
You can declare RPC calls in a schema, that define a set of functions
that take a FlatBuffer as an argument (the request) and return a FlatBuffer
as the response (both of which must be table types):
rpc_service MonsterStorage {
Store(Monster):StoreResponse;
Retrieve(MonsterId):Monster;
}
What code this produces and how it is used depends on language and RPC system
used, there is preliminary support for GRPC through the `--grpc` code generator,
see `grpc/tests` for an example.
### Comments & documentation
May be written as in most C-based languages. Additionally, a triple
comment (`///`) on a line by itself signals that a comment is documentation
for whatever is declared on the line after it
(table/struct/field/enum/union/element), and the comment is output
in the corresponding C++ code. Multiple such lines per item are allowed.
### Attributes
Attributes may be attached to a declaration, behind a field/enum value,
or after the name of a table/struct/enum/union. These may either have
a value or not. Some attributes like `deprecated` are understood by
the compiler; user defined ones need to be declared with the attribute
declaration (like `priority` in the example above), and are
available to query if you parse the schema at runtime.
This is useful if you write your own code generators/editors etc., and
you wish to add additional information specific to your tool (such as a
help text).
Current understood attributes:
- `id: n` (on a table field): manually set the field identifier to `n`.
If you use this attribute, you must use it on ALL fields of this table,
and the numbers must be a contiguous range from 0 onwards.
Additionally, since a union type effectively adds two fields, its
id must be that of the second field (the first field is the type
field and not explicitly declared in the schema).
For example, if the last field before the union field had id 6,
the union field should have id 8, and the unions type field will
implicitly be 7.
IDs allow the fields to be placed in any order in the schema.
When a new field is added to the schema it must use the next available ID.
- `deprecated` (on a field): do not generate accessors for this field
anymore, code should stop using this data. Old data may still contain this
field, but it won't be accessible anymore by newer code. Note that if you
deprecate a field that was previous required, old code may fail to validate
new data (when using the optional verifier).
- `required` (on a non-scalar table field): this field must always be set.
By default, fields do not need to be present in the binary. This is
desirable, as it helps with forwards/backwards compatibility, and
flexibility of data structures. By specifying this attribute, you make non-
presence in an error for both reader and writer. The reading code may access
the field directly, without checking for null. If the constructing code does
not initialize this field, they will get an assert, and also the verifier
will fail on buffers that have missing required fields. Both adding and
removing this attribute may be forwards/backwards incompatible as readers
will be unable read old or new data, respectively, unless the data happens to
always have the field set.
- `force_align: size` (on a struct): force the alignment of this struct
to be something higher than what it is naturally aligned to. Causes
these structs to be aligned to that amount inside a buffer, IF that
buffer is allocated with that alignment (which is not necessarily
the case for buffers accessed directly inside a `FlatBufferBuilder`).
Note: currently not guaranteed to have an effect when used with
`--object-api`, since that may allocate objects at alignments less than
what you specify with `force_align`.
- `force_align: size` (on a vector): force the alignment of this vector to be
something different than what the element size would normally dictate.
Note: Now only work for generated C++ code.
- `bit_flags` (on an unsigned enum): the values of this field indicate bits,
meaning that any unsigned value N specified in the schema will end up
representing 1<<N, or if you don't specify values at all, you'll get
the sequence 1, 2, 4, 8, ...
- `nested_flatbuffer: "table_name"` (on a field): this indicates that the field
(which must be a vector of ubyte) contains flatbuffer data, for which the
root type is given by `table_name`. The generated code will then produce
a convenient accessor for the nested FlatBuffer.
- `flexbuffer` (on a field): this indicates that the field
(which must be a vector of ubyte) contains flexbuffer data. The generated
code will then produce a convenient accessor for the FlexBuffer root.
- `key` (on a field): this field is meant to be used as a key when sorting
a vector of the type of table it sits in. Can be used for in-place
binary search.
- `hash` (on a field). This is an (un)signed 32/64 bit integer field, whose
value during JSON parsing is allowed to be a string, which will then be
stored as its hash. The value of attribute is the hashing algorithm to
use, one of `fnv1_32` `fnv1_64` `fnv1a_32` `fnv1a_64`.
- `original_order` (on a table): since elements in a table do not need
to be stored in any particular order, they are often optimized for
space by sorting them to size. This attribute stops that from happening.
There should generally not be any reason to use this flag.
- 'native_*'. Several attributes have been added to support the [C++ object
Based API](@ref flatbuffers_cpp_object_based_api). All such attributes
are prefixed with the term "native_".
## JSON Parsing
The same parser that parses the schema declarations above is also able
to parse JSON objects that conform to this schema. So, unlike other JSON
parsers, this parser is strongly typed, and parses directly into a FlatBuffer
(see the compiler documentation on how to do this from the command line, or
the C++ documentation on how to do this at runtime).
Besides needing a schema, there are a few other changes to how it parses
JSON:
- It accepts field names with and without quotes, like many JSON parsers
already do. It outputs them without quotes as well, though can be made
to output them using the `strict_json` flag.
- If a field has an enum type, the parser will recognize symbolic enum
values (with or without quotes) instead of numbers, e.g.
`field: EnumVal`. If a field is of integral type, you can still use
symbolic names, but values need to be prefixed with their type and
need to be quoted, e.g. `field: "Enum.EnumVal"`. For enums
representing flags, you may place multiple inside a string
separated by spaces to OR them, e.g.
`field: "EnumVal1 EnumVal2"` or `field: "Enum.EnumVal1 Enum.EnumVal2"`.
- Similarly, for unions, these need to specified with two fields much like
you do when serializing from code. E.g. for a field `foo`, you must
add a field `foo_type: FooOne` right before the `foo` field, where
`FooOne` would be the table out of the union you want to use.
- A field that has the value `null` (e.g. `field: null`) is intended to
have the default value for that field (thus has the same effect as if
that field wasn't specified at all).
- It has some built in conversion functions, so you can write for example
`rad(180)` where ever you'd normally write `3.14159`.
Currently supports the following functions: `rad`, `deg`, `cos`, `sin`,
`tan`, `acos`, `asin`, `atan`.
When parsing JSON, it recognizes the following escape codes in strings:
- `\n` - linefeed.
- `\t` - tab.
- `\r` - carriage return.
- `\b` - backspace.
- `\f` - form feed.
- `\"` - double quote.
- `\\` - backslash.
- `\/` - forward slash.
- `\uXXXX` - 16-bit unicode code point, converted to the equivalent UTF-8
representation.
- `\xXX` - 8-bit binary hexadecimal number XX. This is the only one that is
not in the JSON spec (see http://json.org/), but is needed to be able to
encode arbitrary binary in strings to text and back without losing
information (e.g. the byte 0xFF can't be represented in standard JSON).
It also generates these escape codes back again when generating JSON from a
binary representation.
When parsing numbers, the parser is more flexible than JSON.
A format of numeric literals is more close to the C/C++.
According to the [grammar](@ref flatbuffers_grammar), it accepts the following
numerical literals:
- An integer literal can have any number of leading zero `0` digits.
Unlike C/C++, the parser ignores a leading zero, not interpreting it as the
beginning of the octal number.
The numbers `[081, -00094]` are equal to `[81, -94]` decimal integers.
- The parser accepts unsigned and signed hexadecimal integer numbers.
For example: `[0x123, +0x45, -0x67]` are equal to `[291, 69, -103]` decimals.
- The format of float-point numbers is fully compatible with C/C++ format.
If a modern C++ compiler is used the parser accepts hexadecimal and special
floating-point literals as well:
`[-1.0, 2., .3e0, 3.e4, 0x21.34p-5, -inf, nan]`.
The following conventions for floating-point numbers are used:
- The exponent suffix of hexadecimal floating-point number is mandatory.
- Parsed `NaN` converted to unsigned IEEE-754 `quiet-NaN` value.
Extended floating-point support was tested with:
- x64 Windows: `MSVC2015` and higher.
- x64 Linux: `LLVM 6.0`, `GCC 4.9` and higher.
For details, see [Use in C++](@ref flatbuffers_guide_use_cpp) section.
- For compatibility with a JSON lint tool all numeric literals of scalar
fields can be wrapped to quoted string:
`"1", "2.0", "0x48A", "0x0C.0Ep-1", "-inf", "true"`.
## Guidelines
### Efficiency
FlatBuffers is all about efficiency, but to realize that efficiency you
require an efficient schema. There are usually multiple choices on
how to represent data that have vastly different size characteristics.
It is very common nowadays to represent any kind of data as dictionaries
(as in e.g. JSON), because of its flexibility and extensibility. While
it is possible to emulate this in FlatBuffers (as a vector
of tables with key and value(s)), this is a bad match for a strongly
typed system like FlatBuffers, leading to relatively large binaries.
FlatBuffer tables are more flexible than classes/structs in most systems,
since having a large number of fields only few of which are actually
used is still efficient. You should thus try to organize your data
as much as possible such that you can use tables where you might be
tempted to use a dictionary.
Similarly, strings as values should only be used when they are
truly open-ended. If you can, always use an enum instead.
FlatBuffers doesn't have inheritance, so the way to represent a set
of related data structures is a union. Unions do have a cost however,
so an alternative to a union is to have a single table that has
all the fields of all the data structures you are trying to
represent, if they are relatively similar / share many fields.
Again, this is efficient because non-present fields are cheap.
FlatBuffers supports the full range of integer sizes, so try to pick
the smallest size needed, rather than defaulting to int/long.
Remember that you can share data (refer to the same string/table
within a buffer), so factoring out repeating data into its own
data structure may be worth it.
### Style guide
Identifiers in a schema are meant to translate to many different programming
languages, so using the style of your "main" language is generally a bad idea.
For this reason, below is a suggested style guide to adhere to, to keep schemas
consistent for interoperation regardless of the target language.
Where possible, the code generators for specific languages will generate
identifiers that adhere to the language style, based on the schema identifiers.
- Table, struct, enum and rpc names (types): UpperCamelCase.
- Table and struct field names: snake_case. This is translated to lowerCamelCase
automatically for some languages, e.g. Java.
- Enum values: UpperCamelCase.
- namespaces: UpperCamelCase.
Formatting (this is less important, but still worth adhering to):
- Opening brace: on the same line as the start of the declaration.
- Spacing: Indent by 2 spaces. None around `:` for types, on both sides for `=`.
For an example, see the schema at the top of this file.
## Gotchas
### Schemas and version control
FlatBuffers relies on new field declarations being added at the end, and earlier
declarations to not be removed, but be marked deprecated when needed. We think
this is an improvement over the manual number assignment that happens in
Protocol Buffers (and which is still an option using the `id` attribute
mentioned above).
One place where this is possibly problematic however is source control. If user
A adds a field, generates new binary data with this new schema, then tries to
commit both to source control after user B already committed a new field also,
and just auto-merges the schema, the binary files are now invalid compared to
the new schema.
The solution of course is that you should not be generating binary data before
your schema changes have been committed, ensuring consistency with the rest of
the world. If this is not practical for you, use explicit field ids, which
should always generate a merge conflict if two people try to allocate the same
id.
### Schema evolution examples (tables)
Some examples to clarify what happens as you change a schema:
If we have the following original schema:
table { a:int; b:int; }
And we extend it:
table { a:int; b:int; c:int; }
This is ok. Code compiled with the old schema reading data generated with the
new one will simply ignore the presence of the new field. Code compiled with the
new schema reading old data will get the default value for `c` (which is 0
in this case, since it is not specified).
table { a:int (deprecated); b:int; }
This is also ok. Code compiled with the old schema reading newer data will now
always get the default value for `a` since it is not present. Code compiled
with the new schema now cannot read nor write `a` anymore (any existing code
that tries to do so will result in compile errors), but can still read
old data (they will ignore the field).
table { c:int; a:int; b:int; }
This is NOT ok, as this makes the schemas incompatible. Old code reading newer
data will interpret `c` as if it was `a`, and new code reading old data
accessing `a` will instead receive `b`.
table { c:int (id: 2); a:int (id: 0); b:int (id: 1); }
This is ok. If your intent was to order/group fields in a way that makes sense
semantically, you can do so using explicit id assignment. Now we are compatible
with the original schema, and the fields can be ordered in any way, as long as
we keep the sequence of ids.
table { b:int; }
NOT ok. We can only remove a field by deprecation, regardless of whether we use
explicit ids or not.
table { a:uint; b:uint; }
This is MAYBE ok, and only in the case where the type change is the same size,
like here. If old data never contained any negative numbers, this will be
safe to do.
table { a:int = 1; b:int = 2; }
Generally NOT ok. Any older data written that had 0 values were not written to
the buffer, and rely on the default value to be recreated. These will now have
those values appear to `1` and `2` instead. There may be cases in which this
is ok, but care must be taken.
table { aa:int; bb:int; }
Occasionally ok. You've renamed fields, which will break all code (and JSON
files!) that use this schema, but as long as the change is obvious, this is not
incompatible with the actual binary buffers, since those only ever address
fields by id/offset.
#### Schema evolution examples (unions)
Suppose we have the following schema:
```
union Foo { A, B }
```
We can add another variant at the end.
```
union Foo { A, B, another_a: A }
```
and this will be okay. Old code will not recognize `another_a`.
However if we add `another_a` anywhere but the end, e.g.
```
union Foo { A, another_a: A, B }
```
this is not okay. When new code writes `another_a`, old code will
misinterpret it as `B` (and vice versa). However you can explicitly
set the union's "discriminant" value like so:
```
union Foo { A = 1, another_a: A = 3, B = 2 }
```
This is okay.
```
union Foo { original_a: A = 1, another_a: A = 3, B = 2 }
```
Renaming fields will break code and any saved human readable representations,
such as json files, but the binary buffers will be the same.
<br>
### Testing whether a field is present in a table
Most serialization formats (e.g. JSON or Protocol Buffers) make it very
explicit in the format whether a field is present in an object or not,
allowing you to use this as "extra" information.
FlatBuffers will not write fields that are equal to their default value,
sometimes resulting in significant space savings. However, this also means we
cannot disambiguate the meaning of non-presence as "written default value" or
"not written at all". This only applies to scalar fields since only they support
default values. Unless otherwise specified, their default is 0.
If you care about the presence of scalars, most languages support "optional
scalars." You can set `null` as the default value in the schema. `null` is a
value that's outside of all types, so we will always write if `add_field` is
called. The generated field accessor should use the local language's canonical
optional type.
Some `FlatBufferBuilder` implementations have an option called `force_defaults`
that circumvents this "not writing defaults" behavior you can then use
`IsFieldPresent` to query presence.
/
Another option that works in all languages is to wrap a scalar field in a
struct. This way it will return null if it is not present. This will be slightly
less ergonomic but structs don't take up any more space than the scalar they
represent.
[Interface Definition Language]: https://en.wikipedia.org/wiki/Interface_description_language
## Writing your own code generator.
See [our intermediate representation](@ref intermediate_representation).

File diff suppressed because it is too large Load Diff

149
docs/source/annotation.md Normal file
View File

@@ -0,0 +1,149 @@
# Annotating FlatBuffers
This provides a way to annotate flatbuffer binary data, byte-by-byte, with a
schema. It is useful for development purposes and understanding the details of
the internal format.
## Annotating
Given a `schema`, as either a plain-text (`.fbs`) or a binary schema (`.bfbs`),
and `binary` file(s) that were created by the `schema`. You can annotate them
using:
```sh
flatc --annotate SCHEMA -- BINARY_FILES...
```
This will produce a set of annotated files (`.afb` Annotated FlatBuffer)
corresponding to the input binary files.
### Example
Taken from the [tests/annotated_binary](https://github.com/google/flatbuffers/tree/master/tests/annotated_binary).
```sh
cd tests/annotated_binary
../../flatc --annotate annotated_binary.fbs -- annotated_binary.bin
```
Which will produce a `annotated_binary.afb` file in the current directory.
The `annotated_binary.bin` is the flatbufer binary of the data contained within
`annotated_binary.json`, which was made by the following command:
```sh
..\..\flatc -b annotated_binary.fbs annotated_binary.json
```
## .afb Text Format
Currently there is a built-in text-based format for outputting the annotations.
A full example is shown here:
[`annotated_binary.afb`](https://github.com/google/flatbuffers/blob/master/tests/annotated_binary/annotated_binary.afb)
The data is organized as a table with fixed [columns](#columns) grouped into
Binary [sections](#binary-sections) and [regions](#binary-regions), starting
from the beginning of the binary (offset `0`).
### Columns
The columns are as follows:
1. The offset from the start of the binary, expressed in hexadecimal format
(e.g. `+0x003c`).
The prefix `+` is added to make searching for the offset (compared to some
random value) a bit easier.
2. The raw binary data, expressed in hexadecimal format.
This is in the little endian format the buffer uses internally and what you
would see with a normal binary text viewer.
3. The type of the data.
This may be the type specified in the schema or some internally defined
types:
| Internal Type | Purpose |
|---------------|----------------------------------------------------|
| `VOffset16` | Virtual table offset, relative to the table offset |
| `UOffset32` | Unsigned offset, relative to the current offset |
| `SOffset32` | Signed offset, relative to the current offset |
4. The value of the data.
This is shown in big endian format that is generally written for humans to
consume (e.g. `0x0013`). As well as the "casted" value (e.g. `0x0013 `is
`19` in decimal) in parentheses.
5. Notes about the particular data.
This describes what the data is about, either some internal usage, or tied
to the schema.
### Binary Sections
The file is broken up into Binary Sections, which are comprised of contiguous
[binary regions](#binary-regions) that are logically grouped together. For
example, a binary section may be a single instance of a flatbuffer `Table` or
its `vtable`. The sections may be labelled with the name of the associated type,
as defined in the input schema.
An example of a `vtable` Binary Section that is associated with the user-defined
`AnnotateBinary.Bar` table.
```
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)
```
These are purely annotative, there is no embedded information about these
regions in the flatbuffer itself.
### Binary Regions
Binary regions are contiguous bytes regions that are grouped together to form
some sort of value, e.g. a `scalar` or an array of scalars. A binary region may
be split up over multiple text lines, if the size of the region is large.
#### Annotation Example
Looking at an example binary region:
```
vtable (AnnotatedBinary.Bar):
+0x00A0 | 08 00 | uint16_t | 0x0008 (8) | size of this vtable
```
The first column (`+0x00A0`) is the offset to this region from the beginning of
the buffer.
The second column are the raw bytes (hexadecimal) that make up this region.
These are expressed in the little-endian format that flatbuffers uses for the
wire format.
The third column is the type to interpret the bytes as. For the above example,
the type is `uint16_t` which is a 16-bit unsigned integer type.
The fourth column shows the raw bytes as a compacted, big-endian value. The raw
bytes are duplicated in this fashion since it is more intuitive to read the data
in the big-endian format (e.g., `0x0008`). This value is followed by the decimal
representation of the value (e.g., `(8)`). For strings, the raw string value is
shown instead.
The fifth column is a textual comment on what the value is. As much metadata as
known is provided.
### Offsets
If the type in the 3rd column is of an absolute offset (`SOffet32` or
`Offset32`), the fourth column also shows an `Loc: +0x025A` value which shows
where in the binary this region is pointing to. These values are absolute from
the beginning of the file, their calculation from the raw value in the 4th
column depends on the context.

View File

@@ -0,0 +1,318 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
width="48"
height="48"
viewBox="0 0 12.699999 12.699999"
version="1.1"
id="svg5"
xml:space="preserve"
inkscape:version="1.2.1 (9c6d41e410, 2022-07-14)"
sodipodi:docname="flatbuffer_logo.svg"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg"><sodipodi:namedview
id="namedview7"
pagecolor="#ffffff"
bordercolor="#000000"
borderopacity="0.25"
inkscape:showpageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1"
inkscape:document-units="mm"
showgrid="false"
inkscape:zoom="16"
inkscape:cx="30.03125"
inkscape:cy="31.0625"
inkscape:window-width="2560"
inkscape:window-height="1377"
inkscape:window-x="2552"
inkscape:window-y="-8"
inkscape:window-maximized="1"
inkscape:current-layer="layer1" /><defs
id="defs2"><linearGradient
inkscape:collect="always"
id="linearGradient51996"><stop
style="stop-color:#ff0c0c;stop-opacity:1;"
offset="0"
id="stop51992" /><stop
style="stop-color:#ffc402;stop-opacity:1;"
offset="1"
id="stop51994" /></linearGradient><inkscape:path-effect
effect="mirror_symmetry"
start_point="78.68,115.48"
end_point="78.68,120.48705"
center_point="78.68,117.98353"
id="path-effect36913"
is_visible="true"
lpeversion="1.2"
lpesatellites=""
mode="free"
discard_orig_path="false"
fuse_paths="true"
oposite_fuse="true"
split_items="false"
split_open="false"
link_styles="false" /><inkscape:path-effect
effect="mirror_symmetry"
start_point="78.68,115.48"
end_point="78.68,120.48705"
center_point="78.68,117.98353"
id="path-effect36913-5"
is_visible="true"
lpeversion="1.2"
lpesatellites=""
mode="free"
discard_orig_path="false"
fuse_paths="true"
oposite_fuse="true"
split_items="false"
split_open="false"
link_styles="false" /><linearGradient
inkscape:collect="always"
xlink:href="#linearGradient51996"
id="linearGradient51998"
x1="78.572853"
y1="121.57343"
x2="78.605698"
y2="123.67016"
gradientUnits="userSpaceOnUse" /><linearGradient
inkscape:collect="always"
xlink:href="#linearGradient51996"
id="linearGradient1071"
gradientUnits="userSpaceOnUse"
x1="78.572853"
y1="121.57343"
x2="78.605698"
y2="123.67016" /><linearGradient
inkscape:collect="always"
xlink:href="#linearGradient51996"
id="linearGradient1073"
gradientUnits="userSpaceOnUse"
x1="78.572853"
y1="121.57343"
x2="78.605698"
y2="123.67016" /><linearGradient
inkscape:collect="always"
xlink:href="#linearGradient51996"
id="linearGradient1075"
gradientUnits="userSpaceOnUse"
x1="78.572853"
y1="121.57343"
x2="78.579903"
y2="124.25231" /><linearGradient
inkscape:collect="always"
xlink:href="#linearGradient51996"
id="linearGradient1077"
gradientUnits="userSpaceOnUse"
x1="78.572853"
y1="121.57343"
x2="78.605698"
y2="123.67016" /><linearGradient
inkscape:collect="always"
xlink:href="#linearGradient51996"
id="linearGradient1079"
gradientUnits="userSpaceOnUse"
x1="78.572853"
y1="121.57343"
x2="78.605698"
y2="123.67016" /><linearGradient
inkscape:collect="always"
xlink:href="#linearGradient51996"
id="linearGradient1081"
gradientUnits="userSpaceOnUse"
x1="78.572853"
y1="121.57343"
x2="78.605698"
y2="123.67016" /><linearGradient
inkscape:collect="always"
xlink:href="#linearGradient51996"
id="linearGradient1083"
gradientUnits="userSpaceOnUse"
x1="78.572853"
y1="121.57343"
x2="78.605698"
y2="123.67016" /><linearGradient
inkscape:collect="always"
xlink:href="#linearGradient51996"
id="linearGradient1085"
gradientUnits="userSpaceOnUse"
x1="78.572853"
y1="121.57343"
x2="78.605698"
y2="123.67016" /><linearGradient
inkscape:collect="always"
xlink:href="#linearGradient51996"
id="linearGradient1087"
gradientUnits="userSpaceOnUse"
x1="78.572853"
y1="121.57343"
x2="78.605698"
y2="123.67016" /><linearGradient
inkscape:collect="always"
xlink:href="#linearGradient51996"
id="linearGradient1089"
gradientUnits="userSpaceOnUse"
x1="78.572853"
y1="121.57343"
x2="78.605698"
y2="123.67016" /><linearGradient
inkscape:collect="always"
xlink:href="#linearGradient51996"
id="linearGradient1091"
gradientUnits="userSpaceOnUse"
x1="78.572853"
y1="121.57343"
x2="78.605698"
y2="123.67016" /><linearGradient
inkscape:collect="always"
xlink:href="#linearGradient51996"
id="linearGradient1093"
gradientUnits="userSpaceOnUse"
x1="78.572853"
y1="121.57343"
x2="78.605698"
y2="123.67016" /><linearGradient
inkscape:collect="always"
xlink:href="#linearGradient51996"
id="linearGradient1095"
gradientUnits="userSpaceOnUse"
x1="78.572853"
y1="121.57343"
x2="78.605698"
y2="123.67016" /><linearGradient
inkscape:collect="always"
xlink:href="#linearGradient51996"
id="linearGradient1097"
gradientUnits="userSpaceOnUse"
x1="78.572853"
y1="121.57343"
x2="78.605698"
y2="123.67016" /><linearGradient
inkscape:collect="always"
xlink:href="#linearGradient51996"
id="linearGradient1099"
gradientUnits="userSpaceOnUse"
x1="78.572853"
y1="121.57343"
x2="78.605698"
y2="123.67016" /><linearGradient
inkscape:collect="always"
xlink:href="#linearGradient51996"
id="linearGradient1101"
gradientUnits="userSpaceOnUse"
x1="78.572853"
y1="121.57343"
x2="78.605698"
y2="123.67016" /></defs><g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1"><path
style="fill:#ee2349;fill-opacity:1;stroke-width:0.264583"
d="m 78.679688,115.50977 c -0.120712,0.0641 -0.42793,0.23077 -0.582032,0.34961 -0.183353,0.14139 -0.341667,0.2967 -0.496094,0.48632 -0.09316,0.11439 -0.175141,0.29861 -0.208984,0.46485 -0.05593,0.27473 -0.01958,0.56221 0.01953,0.83984 0.0674,0.47849 0.369141,1.40234 0.369141,1.40234 0,0 -0.370215,0.25236 -0.529297,0.40821 -0.08369,0.082 -0.134669,0.16526 -0.179687,0.27344 -0.06269,0.15064 -0.0906,0.32319 -0.09375,0.48632 -0.0016,0.0822 0.01367,0.26563 0.01367,0.26563 -10e-7,0 0.365376,-0.37098 0.609374,-0.45117 0.135542,-0.0445 0.296791,-0.0606 0.427735,-0.004 0.05341,0.0231 0.05909,0.12539 0.117187,0.12891 0.134803,0.008 0.418285,0.003 0.533204,0 0.114918,0.003 0.3984,0.008 0.533203,0 0.05809,-0.004 0.06378,-0.10581 0.117187,-0.12891 0.130944,-0.0567 0.294146,-0.0406 0.429688,0.004 0.243998,0.0802 0.607422,0.45117 0.607422,0.45117 0,0 0.01722,-0.18343 0.01562,-0.26563 -0.0031,-0.16313 -0.03106,-0.33569 -0.09375,-0.48632 -0.04502,-0.10818 -0.09795,-0.19144 -0.18164,-0.27344 -0.159082,-0.15585 -0.529297,-0.40821 -0.529297,-0.40821 0,0 0.303694,-0.92385 0.371094,-1.40234 0.03911,-0.27763 0.07351,-0.56511 0.01758,-0.83984 -0.03384,-0.16624 -0.115825,-0.35046 -0.208985,-0.46485 -0.154426,-0.18962 -0.31274,-0.34493 -0.496093,-0.48632 -0.154102,-0.11884 -0.46132,-0.28549 -0.582031,-0.34961 z"
id="path36791-6"
sodipodi:nodetypes="csssscssscssscc"
class="UnoptimicedTransforms"
transform="matrix(-1.5867841,0,0,1.5867841,131.19823,-183.26425)"
inkscape:path-effect="#path-effect36913"
inkscape:original-d="m 78.629702,115.48256 c 0,0 0.438268,0.22675 0.632602,0.37661 0.183353,0.1414 0.340934,0.29733 0.49536,0.48695 0.09316,0.11439 0.17524,0.29778 0.209083,0.46402 0.05593,0.27473 0.02088,0.56327 -0.01823,0.8409 -0.0674,0.47849 -0.370162,1.40159 -0.370162,1.40159 0,0 0.369865,0.25228 0.528947,0.40813 0.08369,0.082 0.136292,0.16564 0.18131,0.27381 0.06269,0.15064 0.09017,0.32334 0.09332,0.48647 0.0016,0.0822 -0.01413,0.26601 -0.01413,0.26601 0,0 -0.36491,-0.37107 -0.608908,-0.45126 -0.135542,-0.0445 -0.29706,-0.0607 -0.428004,-0.004 -0.05341,0.0231 -0.06025,0.12485 -0.118343,0.12837 -0.171522,0.0104 -0.582695,-0.002 -0.582695,-0.002 z" /><circle
style="fill:#ffffff;fill-opacity:1;stroke-width:0.461723"
id="path37027"
cx="6.346231"
cy="2.3943322"
r="1.2447678" /><circle
style="font-variation-settings:normal;vector-effect:none;fill:#ffc402;fill-opacity:1;stroke-width:0.141574;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;-inkscape-stroke:none;stop-color:#000000"
id="path37568-5-9-1-3-6-1"
cx="6.5362368"
cy="12.559268"
r="0.11592077" /><g
id="g51228"
style="fill:url(#linearGradient51998);fill-opacity:1"
transform="matrix(1.5867841,0,0,1.5867841,-120.3592,-185.13424)"><circle
style="fill:url(#linearGradient1071);fill-opacity:1;stroke-width:0.224809"
id="path37568"
cx="79.219589"
cy="121.77583"
r="0.18407404" /><circle
style="font-variation-settings:normal;opacity:1;vector-effect:none;fill:url(#linearGradient1073);fill-opacity:1;stroke-width:0.377183;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;-inkscape-stroke:none;stop-color:#000000;stop-opacity:1"
id="path37568-5"
cx="79.928802"
cy="121.81054"
r="0.30883789" /><circle
style="font-variation-settings:normal;vector-effect:none;fill:url(#linearGradient1075);fill-opacity:1;stroke-width:0.518098;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;-inkscape-stroke:none;stop-color:#000000"
id="path37568-5-9"
cx="79.265541"
cy="122.34314"
r="0.42421949" /><circle
style="font-variation-settings:normal;vector-effect:none;fill:url(#linearGradient1077);fill-opacity:1;stroke-width:0.194865;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;-inkscape-stroke:none;stop-color:#000000"
id="path37568-5-9-8"
cx="78.911224"
cy="122.55578"
r="0.15955541" /><circle
style="font-variation-settings:normal;vector-effect:none;fill:url(#linearGradient1079);fill-opacity:1;stroke-width:0.317766;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;-inkscape-stroke:none;stop-color:#000000"
id="path37568-5-9-1"
cx="79.634331"
cy="122.87711"
r="0.26018718" /><circle
style="font-variation-settings:normal;vector-effect:none;fill:url(#linearGradient1081);fill-opacity:1;stroke-width:0.378906;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;-inkscape-stroke:none;stop-color:#000000"
id="path37568-5-9-1-3"
cx="80.265633"
cy="123.65545"
r="0.31024873" /><circle
style="font-variation-settings:normal;vector-effect:none;fill:url(#linearGradient1083);fill-opacity:1;stroke-width:0.177006;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;-inkscape-stroke:none;stop-color:#000000"
id="path37568-5-9-1-3-6"
cx="79.914619"
cy="124.27737"
r="0.14493258" /><circle
style="font-variation-settings:normal;vector-effect:none;fill:url(#linearGradient1085);fill-opacity:1;stroke-width:0.0989143;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;-inkscape-stroke:none;stop-color:#000000"
id="path37568-5-9-1-3-6-6"
cx="80.206474"
cy="124.00723"
r="0.080991074" /><circle
style="font-variation-settings:normal;vector-effect:none;fill:url(#linearGradient1087);fill-opacity:1;stroke-width:0.221224;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;-inkscape-stroke:none;stop-color:#000000"
id="path37568-5-9-1-3-6-0"
cx="79.695312"
cy="123.76383"
r="0.18113838" /><ellipse
style="font-variation-settings:normal;vector-effect:none;fill:url(#linearGradient1089);fill-opacity:1;stroke-width:0.271828;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;-inkscape-stroke:none;stop-color:#000000"
id="path37568-5-9-1-3-6-0-6"
cx="79.60508"
cy="123.37116"
rx="0.22375529"
ry="0.22139755" /><ellipse
style="font-variation-settings:normal;vector-effect:none;fill:url(#linearGradient1091);fill-opacity:1;stroke-width:0.271828;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;-inkscape-stroke:none;stop-color:#000000"
id="path37568-5-9-1-3-6-0-6-7"
cx="79.846291"
cy="123.10796"
rx="0.22375529"
ry="0.22139755" /><ellipse
style="font-variation-settings:normal;vector-effect:none;fill:url(#linearGradient1093);fill-opacity:1;stroke-width:0.244555;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;-inkscape-stroke:none;stop-color:#000000"
id="path37568-5-9-1-3-6-0-6-2"
cx="79.247681"
cy="123.40287"
rx="0.19959654"
ry="0.20088845" /><circle
style="font-variation-settings:normal;vector-effect:none;fill:url(#linearGradient1095);fill-opacity:1;stroke-width:0.243037;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;-inkscape-stroke:none;stop-color:#000000"
id="path37568-5-9-1-2"
cx="80.333969"
cy="122.72621"
r="0.19899905" /><circle
style="font-variation-settings:normal;vector-effect:none;fill:url(#linearGradient1097);fill-opacity:1;stroke-width:0.282009;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;-inkscape-stroke:none;stop-color:#000000"
id="path37568-5-9-1-2-0-9"
cx="80.747818"
cy="122.34882"
r="0.23090924" /><circle
style="font-variation-settings:normal;vector-effect:none;fill:url(#linearGradient1099);fill-opacity:1;stroke-width:0.313683;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;-inkscape-stroke:none;stop-color:#000000"
id="path37568-5-9-1-2-7"
cx="80.58844"
cy="122.97715"
r="0.25684434" /><circle
style="fill:url(#linearGradient1101);fill-opacity:1;stroke-width:0.426803"
id="path37568-5-6"
cx="80.422928"
cy="122.06255"
r="0.34946665" /></g></g></svg>

After

Width:  |  Height:  |  Size: 16 KiB

View File

@@ -1,52 +1,93 @@
Building {#flatbuffers_guide_building}
========
# Building
## Building with CMake
The distribution comes with a `cmake` file that should allow
you to build project/make files for any platform. For details on `cmake`, see
<https://www.cmake.org>. In brief, depending on your platform, use one of
e.g.:
The distribution main build system is configured by
[`cmake`](https://www.cmake.org) which allows you to build the project for any
platform.
### Configuration
Use `cmake` to configure a project based on your environment and platform.
=== "Unix"
```sh
cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release
cmake -G "Visual Studio 10" -DCMAKE_BUILD_TYPE=Release
```
To use `clang` instead of `gcc` you may need to set prepend some environment
variables e.g. `CC=/usr/bin/clang CXX=/usr/bin/clang++ cmake -G "Unix
MakeFiles"`
=== "Windows"
```sh
cmake -G "Visual Studio 17 2022" -DCMAKE_BUILD_TYPE=Release
```
=== "MacOS"
```sh
cmake -G "Xcode" -DCMAKE_BUILD_TYPE=Release
```
Then, build as normal for your platform. This should result in a `flatc`
executable, essential for the next steps.
Note that to use clang instead of gcc, you may need to set up your environment
variables, e.g.
`CC=/usr/bin/clang CXX=/usr/bin/clang++ cmake -G "Unix Makefiles"`.
#### Strict Mode
Optionally, run the `flattests` executable from the root `flatbuffers/`
directory to ensure everything is working correctly on your system. If this
fails, please contact us!
By default, `cmake` will configure targets to **not** build with strict warnings
on (e.g. `-Werror` or `/WX`). This may cause into issues when submitting code
changes since our CI requires the code to compile in strict mode.
Building should also produce two sample executables, `flatsamplebinary` and
`flatsampletext`, see the corresponding `.cpp` files in the
`flatbuffers/samples` directory.
To enable the extra warnings, turn on strict mode with the
`FLATBUFFERS_STRICT_MODE` cmake option.
*Note that you MUST be in the root of the FlatBuffers distribution when you
run 'flattests' or `flatsampletext`, or it will fail to load its files.*
### Make all warnings into errors
By default all Flatbuffers `cmake` targets are **not** built with the `-Werror`
(or `/WX` for MSVC) flag that treats any warning as an error. This allows more
flexibility for users of Flatbuffers to use newer compilers and toolsets that
may add new warnings that would cause a build failure.
To enable a stricter build that does treat warnings as errors, set the
`FLATBUFFERS_STRICT_MODE` `cmake` compliation flag to `ON`.
```
cmake . -DFLATBUFFERS_STRICT_MODE=ON
```cmake
cmake -DFLATBUFFERS_STRICT_MODE=ON
```
Our CI builds run with strict mode on, ensuring the code that is committed to
the project is as portable and warning free as possible. Thus developers
contributing to the project should enable strict mode locally before making a
PR.
### Building
Once the project files are generated, build as normal for your platform.
=== "Unix"
```sh
make -j
```
=== "Windows"
```sh
msbuild.exe FlatBuffers.sln
```
=== "MacOS"
```sh
xcodebuild -toolchain clang -configuration Release
```
## Building with Bazel
You can use [Bazelisk](https://github.com/bazelbuild/bazelisk) to manage your Bazel environment.
For Swift support, you also need Clang and [Swift SDK](https://download.swift.org/).
```sh
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 //...
```
If you are unsure which versions to use, check our CI config at `.bazelci/presubmit.yml`.
## Building with VCPKG
@@ -61,17 +102,7 @@ You can download and install flatbuffers using the [vcpkg](https://github.com/Mi
The flatbuffers port in vcpkg is kept up to date by Microsoft team members and community contributors.
If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository.
## Downloading binaries
You can download the binaries from the
[GitHub release page](https://github.com/google/flatbuffers/releases).
We generate [SLSA3 signatures](slsa.dev) using the OpenSSF's [slsa-framework/slsa-github-generator](https://github.com/slsa-framework/slsa-github-generator). To verify the binaries:
1. Install the verification tool from [slsa-framework/slsa-verifier#installation](https://github.com/slsa-framework/slsa-verifier#installation)
1. Download the file named `attestation.intoto.jsonl` from the GitHub release
1. Run:
```shell
$ slsa-verifier -artifact-path <downloaded.zip> -provenance attestation.intoto.jsonl -source github.com/google/flatbuffers -tag <version>
PASSED: Verified SLSA provenance
## Building for Android
@@ -96,7 +127,7 @@ also compile/link `src/idl_parser.cpp` (and `src/idl_gen_text.cpp` if you
also want to be able convert binary to text).
To see how to include FlatBuffers in any of our supported languages, please
view the [Tutorial](@ref flatbuffers_guide_tutorial) and select your appropriate
view the [Tutorial](tutorial.md) and select your appropriate
language using the radio buttons.
### Using in CMake-based projects
@@ -125,9 +156,22 @@ When build your project the `flatbuffers` library will be compiled and linked
to a target as part of your project.
#### Override default depth limit of nested objects
To override [the depth limit of recursion](@ref flatbuffers_guide_use_cpp),
To override [the depth limit of recursion](languages/cpp.md),
add this directive:
```cmake
set(FLATBUFFERS_MAX_PARSING_DEPTH 16)
```
to `CMakeLists.txt` file before `add_subdirectory(${FLATBUFFERS_SRC_DIR})` line.
## Downloading binaries
You can download the binaries from the
[GitHub release page](https://github.com/google/flatbuffers/releases).
We generate [SLSA3 signatures](http://slsa.dev) using the OpenSSF's [slsa-framework/slsa-github-generator](https://github.com/slsa-framework/slsa-github-generator). To verify the binaries:
1. Install the verification tool from [slsa-framework/slsa-verifier#installation](https://github.com/slsa-framework/slsa-verifier#installation)
1. Download the file named `attestation.intoto.jsonl` from the GitHub release
1. Run:
```shell
$ slsa-verifier -artifact-path <downloaded.zip> -provenance attestation.intoto.jsonl -source github.com/google/flatbuffers -tag <version>
PASSED: Verified SLSA provenance
```

View File

@@ -0,0 +1,80 @@
# Contributing
We encourage community contributions to FlatBuffers through pull requests at the
main
[http://github.com/google/flatbuffers](http://github.com/google/flatbuffers)
repository.
!!! note
The FlatBuffers project is not staffed by any full time Google employee, and
is managed by a small team of 20%ers. So response time and expertise vary.
## Before you contribute
Before we can use your contributions, you __must__ sign one of the following license agreements. The agreements are self-served at the following links.
Our code review process will automatically check if you have signed the CLA, so
don't fret. Though it may be prudent to check before spending a lot of time on
contribution.
### Individual Contributions
For individuals, the [Google Individual
Contributor License Agreement
(CLA)](https://cla.developers.google.com/about/google-individual?csw=1) which is
self served at the link. The CLA is required since you own the copyright to your
changes, even after your contribution becomes part of our codebase, so we need
your permission to use and distribute your code.
### Corporate Contributions
Contributions made by corporations are covered by the [Google Software Grant and
Corporate Contributor License
Agreement](https://cla.developers.google.com/about/google-corporate).
## Code Reviews
All submissions require a code review via Github Pull Requests.
1. Please adhere to the [Google Style Guide](https://google.github.io/styleguide/cppguide.html) for the language(s) you are submitting in.
2. Keep PRs small and focused. Its good practice and makes it more likely your PR will be approved.
3. Please add tests if possible.
4. Include descriptive commit messages and context to the change/issues fixed.
## Documentation
FlatBuffers uses [MkDocs](https://www.mkdocs.org/) to generate the static
documentation pages served at
[https://flatbuffers.dev](https://flatbuffers.dev). Specifically, we use the
[Material for MkDocs](https://squidfunk.github.io/mkdocs-material/) framework.
The documentation source is contained in the main repo under the
[docs/](https://github.com/google/flatbuffers/tree/master/docs) directory. This
[automatically](https://github.com/google/flatbuffers/blob/46cc3d6432da17cca7694777dcce12e49dd48387/.github/workflows/docs.yml#L6-L11) get built and published when the commit is made.
### Local Development
We encourage contributors to keep the documentation up-to-date as well, and it
is easy to with `MkDocs` local building and serving tools.
First install `mkdocs-material` (see
[Installation](https://squidfunk.github.io/mkdocs-material/getting-started/) for
other ways)
```
pip install mkdocs-material
pip install mkdocs-redirects
```
Then, in the `root` directory of flatbuffers, run
```
mkdocs serve -f docs/mkdocs.yml
```
This will continually watch the repo for changes to the documentation and serve
the rendered pages locally.
Submit your documentation changes with your code changes and they will
automatically get published when your code is submitted.

File diff suppressed because it is too large Load Diff

View File

@@ -1,254 +0,0 @@
<!-- 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.
-->
<doxygenlayout version="1.0">
<navindex>
<tab type="mainpage" visible="no" title=""/>
<tab type="usergroup" url="" title="Programmer's Guide">
<tab type="user" url="@ref flatbuffers_guide_building"
title="Building"/>
<tab type="user" url="@ref flatbuffers_guide_tutorial" title="Tutorial"/>
<tab type="user" url="@ref flatbuffers_guide_using_schema_compiler"
title="Using the schema compiler"/>
<tab type="user" url="@ref flatbuffers_guide_writing_schema"
title="Writing a schema"/>
<tab type="user" url="@ref flatbuffers_guide_use_cpp"
title="Use in C++"/>
<tab type="user" url="@ref flatbuffers_guide_use_c"
title="Use in C"/>
<tab type="user" url="@ref flatbuffers_guide_use_go"
title="Use in Go"/>
<tab type="user" url="@ref flatbuffers_guide_use_java"
title="Use in Java"/>
<tab type="user" url="@ref flatbuffers_guide_use_c-sharp"
title="Use in C#"/>
<tab type="user" url="@ref flatbuffers_guide_use_javascript"
title="Use in JavaScript"/>
<tab type="user" url="@ref flatbuffers_guide_use_typescript"
title="Use in TypeScript"/>
<tab type="user" url="@ref flatbuffers_guide_use_php"
title="Use in PHP"/>
<tab type="user" url="@ref flatbuffers_guide_use_python"
title="Use in Python"/>
<tab type="user" url="@ref flatbuffers_guide_use_dart"
title="Use in Dart"/>
<tab type="user" url="@ref flatbuffers_guide_use_lua"
title="Use in Lua"/>
<tab type="user" url="@ref flatbuffers_guide_use_lobster"
title="Use in Lobster"/>
<tab type="user" url="@ref flatbuffers_guide_use_rust"
title="Use in Rust"/>
<tab type="user" url="@ref flatbuffers_guide_use_swift"
title="Use in Swift"/>
<tab type="user" url="@ref flexbuffers"
title="FlexBuffers (Schema-less version)"/>
<tab type="usergroup" url="" title="gRPC">
<tab type="user" url="@ref flatbuffers_grpc_guide_use_cpp"
title="Use in C++"/>
</tab>
</tab>
<tab type="user" url="@ref flatbuffers_support"
title="Platform / Language / Feature support"/>
<tab type="user" url="@ref flatbuffers_benchmarks"
title="Benchmarks"/>
<tab type="user" url="@ref flatbuffers_white_paper"
title="FlatBuffers white paper"/>
<tab type="user" url="@ref flatbuffers_internals"
title="FlatBuffers internals"/>
<tab type="user" url="@ref intermediate_representation"
title="Intermediate Representation"/>
<tab type="user" url="@ref flatbuffers_grammar"
title="Grammar of the schema language"/>
<tab type="usergroup" url="" title="API Reference">
<tab type="modules" visible="yes" title="APIs" intro=""/>
<tab type="classes" visible="yes" title="">
<tab type="classlist" visible="yes" title="" intro=""/>
<tab type="classindex" visible="$ALPHABETICAL_INDEX" title=""/>
<tab type="hierarchy" visible="yes" title="" intro=""/>
<tab type="classmembers" visible="yes" title="" intro=""/>
</tab>
</tab>
<tab type="user" url="@ref contributing" title="Contributing"/>
</navindex>
<!-- Layout definition for a class page -->
<class>
<briefdescription visible="yes"/>
<includes visible="$SHOW_INCLUDE_FILES"/>
<inheritancegraph visible="$CLASS_GRAPH"/>
<collaborationgraph visible="$COLLABORATION_GRAPH"/>
<detaileddescription title=""/>
<memberdecl>
<nestedclasses visible="yes" title=""/>
<publictypes title=""/>
<services title=""/>
<interfaces title=""/>
<publicslots title=""/>
<signals title=""/>
<publicmethods title=""/>
<publicstaticmethods title=""/>
<publicattributes title=""/>
<publicstaticattributes title=""/>
<protectedtypes title=""/>
<protectedslots title=""/>
<protectedmethods title=""/>
<protectedstaticmethods title=""/>
<protectedattributes title=""/>
<protectedstaticattributes title=""/>
<packagetypes title=""/>
<packagemethods title=""/>
<packagestaticmethods title=""/>
<packageattributes title=""/>
<packagestaticattributes title=""/>
<properties title=""/>
<events title=""/>
<privatetypes title=""/>
<privateslots title=""/>
<privatemethods title=""/>
<privatestaticmethods title=""/>
<privateattributes title=""/>
<privatestaticattributes title=""/>
<friends title=""/>
<related title="" subtitle=""/>
<membergroups visible="yes"/>
</memberdecl>
<memberdef>
<inlineclasses title=""/>
<typedefs title=""/>
<enums title=""/>
<services title=""/>
<interfaces title=""/>
<constructors title=""/>
<functions title=""/>
<related title=""/>
<variables title=""/>
<properties title=""/>
<events title=""/>
</memberdef>
<allmemberslink visible="yes"/>
<usedfiles visible="$SHOW_USED_FILES"/>
<authorsection visible="yes"/>
</class>
<!-- Layout definition for a namespace page -->
<namespace>
<briefdescription visible="yes"/>
<memberdecl>
<nestednamespaces visible="yes" title=""/>
<constantgroups visible="yes" title=""/>
<classes visible="yes" title=""/>
<typedefs title=""/>
<enums title=""/>
<functions title=""/>
<variables title=""/>
<membergroups visible="yes"/>
</memberdecl>
<detaileddescription title=""/>
<memberdef>
<inlineclasses title=""/>
<typedefs title=""/>
<enums title=""/>
<functions title=""/>
<variables title=""/>
</memberdef>
<authorsection visible="yes"/>
</namespace>
<!-- Layout definition for a file page -->
<file>
<briefdescription visible="yes"/>
<includes visible="$SHOW_INCLUDE_FILES"/>
<includegraph visible="$INCLUDE_GRAPH"/>
<includedbygraph visible="$INCLUDED_BY_GRAPH"/>
<sourcelink visible="yes"/>
<detaileddescription title=""/>
<memberdecl>
<classes visible="yes" title=""/>
<namespaces visible="yes" title=""/>
<constantgroups visible="yes" title=""/>
<defines title=""/>
<typedefs title=""/>
<enums title=""/>
<functions title=""/>
<variables title=""/>
<membergroups visible="yes"/>
</memberdecl>
<memberdef>
<inlineclasses title=""/>
<defines title=""/>
<typedefs title=""/>
<enums title=""/>
<functions title=""/>
<variables title=""/>
</memberdef>
<authorsection/>
</file>
<!-- Layout definition for a group page -->
<group>
<briefdescription visible="yes"/>
<groupgraph visible="$GROUP_GRAPHS"/>
<detaileddescription title=""/>
<memberdecl>
<nestedgroups visible="yes" title=""/>
<dirs visible="yes" title=""/>
<files visible="yes" title=""/>
<namespaces visible="yes" title=""/>
<classes visible="yes" title=""/>
<defines title=""/>
<typedefs title=""/>
<enums title=""/>
<enumvalues title=""/>
<functions title=""/>
<variables title=""/>
<signals title=""/>
<publicslots title=""/>
<protectedslots title=""/>
<privateslots title=""/>
<events title=""/>
<properties title=""/>
<friends title=""/>
<membergroups visible="yes"/>
</memberdecl>
<memberdef>
<pagedocs/>
<inlineclasses title=""/>
<defines title=""/>
<typedefs title=""/>
<enums title=""/>
<enumvalues title=""/>
<functions title=""/>
<variables title=""/>
<signals title=""/>
<publicslots title=""/>
<protectedslots title=""/>
<privateslots title=""/>
<events title=""/>
<properties title=""/>
<friends title=""/>
</memberdef>
<authorsection visible="yes"/>
</group>
<!-- Layout definition for a directory page -->
<directory>
<briefdescription visible="yes"/>
<directorygraph visible="yes"/>
<memberdecl>
<dirs visible="yes"/>
<files visible="yes"/>
</memberdecl>
<detaileddescription title=""/>
</directory>
</doxygenlayout>

276
docs/source/evolution.md Normal file
View File

@@ -0,0 +1,276 @@
# Evolution
FlatBuffers enables the [schema](schema.md) to evolve over time while still
maintaining forwards and backwards compatibility with old flatbuffers.
Some rules must be followed to ensure the evolution of a schema is valid.
## Rules
Adding new tables, vectors, structs to the schema is always allowed. Its only
when you add a new field to a [`table`](schema.md#tables) that certain rules
must be followed.
### Addition
**New fields MUST be added to the end of the table definition.**
This allows older data to still be read correctly (giving you the default value
of the added field if accessed).
Older code will simply ignore the new field in the flatbuffer.
You can ignore this rule if you use the `id` attribute on all the fields of a
table.
### Removal
**You MUST not remove a field from the schema, even if you don't use it
anymore.** You simply stop writing them to the buffer.
Its encouraged to mark the field deprecated by adding the `deprecated`
attribute. This will skip the generation of accessors and setters in the code,
to enforce the field not to be used any more.
### Name Changes
Its generally OK to change the name of tables and fields, as these are not
serialized to the buffer. It may break code that would have to be refactored
with the updated name.
## Examples
The following examples uses a base schema and attempts to evolve it a few times.
The versions are tracked by `V1`, `V2`, etc.. and `CodeV1` means code compiled
against the `V1` schema.
### Table Evolution
Lets start with a simple table `T` with two fields.
```c++ title="Schema V1"
table T {
a:int;
b:int;
}
```
=== "Well Evolved"
First lets extend the table with a new field.
```c++ title="Schema V2"
table T {
a:int;
b:int;
c:int;
}
```
This is OK. `CodeV1` reading `V2` data will simply ignore the presence of the
new field `c`. `CodeV2` reading `V1` data will get a default value (0) when
reading `c`.
```c++ title="Schema V3"
table T {
a:int (deprecated);
b:int;
c:int;
}
```
This is OK, removing field `a` via deprecation. `CodeV1`, `CodeV2` and `CodeV3`
reading `V3` data will now always get the default value of `a`, since it is not
present. `CodeV3` cannot write `a` anymore. `CodeV3` reading old data (`V1` or
`V2`) will not be able to access the field anymore, since no generated accessors
are omitted.
=== "Improper Addition"
Add a new field, but this time at the beginning.
```c++ title="Schema V2"
table T {
c:int;
a:int;
b:int;
}
```
This is NOT OK, as it makes `V2` incompatible. `CodeV1` reading `V2` data
will access `a` but will read `c` data.
`CodeV2` reading `V1` data will access `c` but will read `a` data.
=== "Improper Deletion"
Remove a field from the schema.
```c++ title="Schema V2"
table T {
b:int;
}
```
This is NOT OK. `CodeV1` reading `V2` data will access `a` but read `b` data.
`CodeV2` reading `V1` data will access `b` but will read `a` data.
=== "Proper Reordering"
Lets add a new field to the beginning, but use `id` attributes.
```c++ title="Schema V2"
table T {
c:int (id: 2);
a:int (id: 0);
b:int (id: 1);
}
```
This is OK. This adds the a new field in the beginning, but because all the
`id` attributes were added, it is OK.
=== "Changing Types"
Let change the types of the fields.
```c++ title="Schema V2"
table T {
a:uint;
b:uint;
}
```
This is MAYBE OK, and only in the case where the type change is the same
width. This is tricky if the `V1` data contained any negative numbers. So
this should be done with care.
=== "Changing Defaults"
Lets change the default values of the existing fields.
```c++ title="Schema V2"
table T {
a:int = 1;
b:int = 2;
}
```
This is NOT OK. Any `V1` data that did not have a value written to the
buffer relied on generated code to provide the default value.
There MAY be cases where this is OK, if you control all the producers and
consumers, and you can update them in tandem.
=== "Renaming Fields"
Lets change the name of the fields
```c++ title="Schema V2"
table T {
aa:int;
bb:int;
}
```
This is generally OK. You've renamed fields will break all code and JSON
files that use this schema, but you can refactor those without affecting the
binary data, since the binary only address fields by id and offset, not by
names.
### Union Evolution
Lets start with a simple union `U` with two members.
```c++ title="Schema V1"
union U {
A,
B
}
```
=== "Well Evolved"
Lets add a another variant to the end.
```c++ title="Schema V2"
union U {
A,
B,
another_a: A
}
```
This is OK. `CodeV1` will not recognize the `another_a`.
=== "Improper Evolved"
Lets add a another variant to the middle.
```c++ title="Schema V2"
union U {
A,
another_a: A,
B
}
```
This is NOT OK. `CodeV1` reading `V2` data will interpret `B` as `another_a`.
`CodeV2` reading `V1` data will interpret `another_a` as `B`.
=== "Evolved With Discriminant"
Lets add a another variant to the middle, this time adding a union "discriminant".
```c++ title="Schema V2"
union U {
A = 1,
another_a: A = 3,
B = 2
}
```
This is OK. Its like you added it to the end, but using the discriminant
value to physically place it elsewhere in the union.
## Version Control
FlatBuffers relies on new field declarations being added at the end, and earlier
declarations to not be removed, but be marked deprecated when needed. We think
this is an improvement over the manual number assignment that happens in
Protocol Buffers (and which is still an option using the `id` attribute
mentioned above).
One place where this is possibly problematic however is source control. If user
`A` adds a field, generates new binary data with this new schema, then tries to
commit both to source control after user `B` already committed a new field also,
and just auto-merges the schema, the binary files are now invalid compared to
the new schema.
The solution of course is that you should not be generating binary data before
your schema changes have been committed, ensuring consistency with the rest of
the world. If this is not practical for you, use explicit field `id`s, which
should always generate a merge conflict if two people try to allocate the same
id.
## Checking Conformity
To check that schema are properly evolved, the [`flatc`](flatc.md) compiler has
a [option](flatc.md#additional-options) to do just that:
```sh
--conform FILE
```
Where `FILE` is the base schema the rest of the input schemas must evolve from.
It returns `0` if they are properly evolved, otherwise returns a non-zero value
and provides errors on the reason why the schema are not properly evolved.
As an example, the following checks if `schema_v2.fbs` is properly evolved from
`schema_v1.fbs`.
```sh
flatc --conform schema_v1.fbs schema_v2.fbs
```

View File

@@ -1,70 +1,91 @@
Using the schema compiler {#flatbuffers_guide_using_schema_compiler}
=========================
# FlatBuffers Compiler (`flatc`)
Usage:
The main compiler for FlatBuffers is called `flatc` and is used to convert
schema definitions into generated code files for a variety of languages.
flatc [ GENERATOR OPTIONS ] [ -o PATH ] [ -I PATH ] FILES...
[ -- FILES...]
After [building](building.md) `flatc`, it is used as follows:
The files are read and parsed in order, and can contain either schemas
or data (see below). Data files are processed according to the definitions of
the most recent schema specified.
```sh
flatc [ GENERATOR_OPTIONS ] [ -o PATH ] [- I PATH ]
FILES...
[ -- BINARY_FILES... ]
```
`--` indicates that the following files are binary files in
FlatBuffer format conforming to the schema indicated before it.
* The `GENERATOR_OPTIONS` specify the language(s) to compile code for as well as
various features to enable/disable.
Depending on the flags passed, additional files may
be generated for each file processed:
* The `-o PATH` specifies the path where the generated files are placed. It
defaults to the current path if not specified.
For any schema input files, one or more generators can be specified:
* The `-I PATH` specifies the paths where included schema files are located. It
defaults to the current path if not specified.
- `--cpp`, `-c` : Generate a C++ header for all definitions in this file (as
`filename_generated.h`).
## Input Files
- `--java`, `-j` : Generate Java code.
`FILES...` specifies one or more schema or data files to process. They are
processed in the order provided.
- `--kotlin` , `--kotlin-kmp` : Generate Kotlin code.
### Schema Files
- `--csharp`, `-n` : Generate C# code.
For schema files, language specifiers indicate what languages to generate code
for.
- `--go`, `-g` : Generate Go code.
* `--cpp`: C++
* `--java`: Java
* `--kotlin`: Kotlin
* `--csharp`: C#
* `--go`: Golang
* `--python`: Python
* `--js`: JavaScript
* `--ts`: TypeScript
* `--php`: PHP
* `--dart`: Dart
* `--lua`: Lua
* `--lobster`: Lobster
* `--rust`: Rust
* `--swift`: Swift
* `--nim`: Nim
- `--python`, `-p` : Generate Python code.
Additionally, adding:
- `--js`, `-s` : Generate JavaScript code.
* `--grpc` Will generate RPC stub code for gRPC (not available in all
languages)
- `--ts`, `-T` : Generate TypeScript code.
### Data Files
- `--php` : Generate PHP code.
If `FILES...` contain data files, they can be exported to either a binary or
JSON representation.
- `--grpc` : Generate RPC stub code for GRPC.
* `--binary`, `-b`: Generate a binary file containing a serialized flatbuffer.
* `--json`, `-j`: Generate JSON file from a serialized flatbuffer.
- `--dart`, `-d` : Generate Dart code.
Both options require the corresponding schema file to be included first in the
list of `FILES...`.
- `--lua`, `-l` : Generate Lua code.
=== "To Binary"
- `--lobster` : Generate Lobster code.
To serialize the JSON data in `mydata.json` using the schema `myschema.fbs`:
```sh
flatc --binary myschema.fbs mydata.json
```
- `--rust`, `-r` : Generate Rust code.
This will generate a `mydata_wire.bin` file containing the serialized
flatbuffer data.
- `--swift` : Generate Swift code.
=== "To JSON"
- `--nim` : Generate Nim code.
To convert the serialized binary flatbuffer `mydata.bin` using the schema
`myschema.fbs` to JSON:
```sh
flatc --json myschema.fbs mydata.bin
```
This will generate a `mydata.json` file.
For any data input files:
- `--binary`, `-b` : If data is contained in this file, generate a
`filename.bin` containing the binary flatbuffer (or a different extension
if one is specified in the schema).
- `--json`, `-t` : If data is contained in this file, generate a
`filename.json` representing the data in the flatbuffer.
- `--jsonschema` : Generate Json schema
Additional options:
### Additional options
- `-o PATH` : Output all generated files to PATH (either absolute, or
relative to the current directory). If omitted, PATH will be the
@@ -96,10 +117,10 @@ Additional options:
- `--scoped-enums` : Use C++11 style scoped and strongly typed enums in
generated C++. This also implies `--no-prefix`.
- `--no-emit-min-max-enum-values` : Disable generation of MIN and MAX
enumerated values for scoped enums and prefixed enums.
- `--gen-includes` : (deprecated), this is the default behavior.
If the original behavior is required (no include
statements) use `--no-includes.`
@@ -238,5 +259,45 @@ Additional options:
- `--python-typing` : Generate Python type annotations
Additional gRPC options:
- `--grpc-filename-suffix`: `[C++]` An optional suffix for the generated
files' names. For example, compiling gRPC for C++ with
`--grpc-filename-suffix=.fbs` will generate `{name}.fbs.h` and
`{name}.fbs.cc` files.
- `--grpc-additional-header`: `[C++]` Additional headers to include in the
generated files.
- `--grpc-search-path`: `[C++]` An optional prefix for the gRPC runtime path.
For example, compiling gRPC for C++ with `--grpc-search-path=some/path` will
generate the following includes:
```cpp
#include "some/path/grpcpp/impl/codegen/async_stream.h"
#include "some/path/grpcpp/impl/codegen/async_unary_call.h"
#include "some/path/grpcpp/impl/codegen/method_handler.h"
...
```
- `--grpc-use-system-headers`: `[C++]` Whether to generate `#include <header>`
instead of `#include "header.h"` for all headers when compiling gRPC for
C++. For example, compiling gRPC for C++ with `--grpc-use-system-headers`
will generate the following includes:
```cpp
#include <some/path/grpcpp/impl/codegen/async_stream.h>
#include <some/path/grpcpp/impl/codegen/async_unary_call.h>
#include <some/path/grpcpp/impl/codegen/method_handler.h>
...
```
NOTE: This option can be negated with `--no-grpc-use-system-headers`.
- `--grpc-python-typed-handlers`: `[Python]` Whether to generate the typed
handlers that use the generated Python classes instead of raw bytes for
requests/responses.
NOTE: short-form options for generators are deprecated, use the long form
whenever possible.

View File

@@ -163,7 +163,7 @@ map.get("unknown").isNull(); // true
# Binary encoding
A description of how FlexBuffers are encoded is in the
[internals](@ref flatbuffers_internals) document.
[internals](internals.md) document.
# Nesting inside a FlatBuffer

View File

@@ -1,29 +0,0 @@
Use in C++ {#flatbuffers_grpc_guide_use_cpp}
==========
## Before you get started
Before diving into the FlatBuffers gRPC usage in C++, you should already be
familiar with the following:
- FlatBuffers as a serialization format
- [gRPC](http://www.grpc.io/docs/) usage
## Using the FlatBuffers gRPC C++ library
NOTE: The examples below are also in the `grpc/samples/greeter` directory.
We will illustrate usage with the following schema:
@include grpc/samples/greeter/greeter.fbs
When we run `flatc`, we pass in the `--grpc` option and generage an additional
`greeter.grpc.fb.h` and `greeter.grpc.fb.cc`.
Example server code looks like this:
@include grpc/samples/greeter/server.cpp
Example client code looks like this:
@include grpc/samples/greeter/client.cpp

73
docs/source/grammar.md Normal file
View File

@@ -0,0 +1,73 @@
## EBNF
```ebnf
schema = include* ( namespace_decl | type_decl | enum_decl | root_decl |
file_extension_decl | file_identifier_decl |
attribute_decl | rpc_decl | object )*
include = `include` string_constant `;`
namespace_decl = `namespace` ident ( `.` ident )* `;`
attribute_decl = `attribute` ident | `"` ident `"` `;`
type_decl = ( `table` | `struct` ) ident metadata `{` field_decl+ `}`
enum_decl = ( `enum` ident `:` type | `union` ident ) metadata `{`
commasep( enumval_decl ) `}`
root_decl = `root_type` ident `;`
field_decl = ident `:` type [ `=` scalar ] metadata `;`
rpc_decl = `rpc_service` ident `{` rpc_method+ `}`
rpc_method = ident `(` ident `)` `:` ident metadata `;`
type = `bool` | `byte` | `ubyte` | `short` | `ushort` | `int` | `uint` |
`float` | `long` | `ulong` | `double` | `int8` | `uint8` | `int16` |
`uint16` | `int32` | `uint32`| `int64` | `uint64` | `float32` |
`float64` | `string` | `[` type `]` | ident
enumval_decl = ident [ `=` integer_constant ] metadata
metadata = [ `(` commasep( ident [ `:` single_value ] ) `)` ]
scalar = boolean_constant | integer_constant | float_constant
object = `{` commasep( ident `:` value ) `}`
single_value = scalar | string_constant
value = single_value | object | `[` commasep( value ) `]`
commasep(x) = [ x ( `,` x )\* ]
file_extension_decl = `file_extension` string_constant `;`
file_identifier_decl = `file_identifier` string_constant `;`
string_constant = `\".*?\"`
ident = `[a-zA-Z_][a-zA-Z0-9_]*`
`[:digit:]` = `[0-9]`
`[:xdigit:]` = `[0-9a-fA-F]`
dec_integer_constant = `[-+]?[:digit:]+`
hex_integer_constant = `[-+]?0[xX][:xdigit:]+`
integer_constant = dec_integer_constant | hex_integer_constant
dec_float_constant = `[-+]?(([.][:digit:]+)|([:digit:]+[.][:digit:]*)|([:digit:]+))([eE][-+]?[:digit:]+)?`
hex_float_constant = `[-+]?0[xX](([.][:xdigit:]+)|([:xdigit:]+[.][:xdigit:]*)|([:xdigit:]+))([pP][-+]?[:digit:]+)`
special_float_constant = `[-+]?(nan|inf|infinity)`
float_constant = dec_float_constant | hex_float_constant | special_float_constant
boolean_constant = `true` | `false`
```

View File

@@ -1,23 +0,0 @@
/// @defgroup flatbuffers_cpp_api C++ API
/// @brief FlatBuffers API for C++
/// @defgroup flatbuffers_csharp_api C# API
/// @brief FlatBuffers API for C#
/// @defgroup flatbuffers_go_api Go API
/// @brief FlatBuffers API for Go
/// @defgroup flatbuffers_java_api Java API
/// @brief FlatBuffers API for Java
/// @defgroup flatbuffers_javascript_api JavaScript API
/// @brief FlatBuffers API for JavaScript
/// @defgroup flatbuffers_typescript_api TypeScript API
/// @brief FlatBuffers API for TypeScript
/// @defgroup flatbuffers_php_api PHP API
/// @brief FlatBuffers API for PHP
/// @defgroup flatbuffers_python_api Python API
/// @brief FlatBuffers API for Python

59
docs/source/index.md Normal file
View File

@@ -0,0 +1,59 @@
# Overview
FlatBuffers is an efficient cross platform serialization library for C++, C#, C,
Go, Java, Kotlin, JavaScript, Lobster, Lua, TypeScript, PHP, Python, Rust and
Swift. It was originally created at Google for game development and other
performance-critical applications.
It is available as Open Source on
[GitHub](https://github.com/google/flatbuffers) under the Apache license v2.0.
## Why Use FlatBuffers?
<div class="grid cards" markdown>
- :material-clock-fast:{ .lg .middle } **Access to serialized data without
parsing/unpacking**
---
Access the data directly without unpacking or parsing.
- :material-memory:{ .lg .middle } **Memory Efficiency and Speed**
---
The only memory needed to access your data is that of the buffer. No heap is
required.
- :material-compare-horizontal:{ .lg .middle } **Backwards and Forwards
Compatibility**
---
The only memory needed to access your data is that of the buffer. No heap is
required.
- :material-scale-off:{ .lg .middle } **Small Footprint**
---
Minimal dependencies and small code footprint.
</div>
## Why not use...
=== "Protocol Buffers"
Protocol Buffers is indeed relatively similar to FlatBuffers, with the primary
difference being that FlatBuffers does not need a parsing/unpacking step to a
secondary representation before you can access data, often coupled with
per-object memory allocation. The code is an order of magnitude bigger, too.
=== "JSON"
JSON is very readable (which is why we use it as our optional text format) and
very convenient when used together with dynamically typed languages (such as
JavaScript). When serializing data from statically typed languages, however,
JSON not only has the obvious drawback of runtime inefficiency, but also forces
you to write more code to access data (counterintuitively) due to its
dynamic-typing serialization system. In this context, it is only a better choice
for systems that have very little to no information ahead of time about what
data needs to be stored.

View File

@@ -316,7 +316,7 @@ that may further help clarify the format.
# FlexBuffers
The [schema-less](@ref flexbuffers) version of FlatBuffers have their
The [schema-less](flexbuffers.md) version of FlatBuffers have their
own encoding, detailed here.
It shares many properties mentioned above, in that all data is accessed
@@ -464,5 +464,3 @@ So for example, the integer value `13` as root would be:
uint8_t 13, 4, 1 // Value, type, root byte width.
<br>

View File

@@ -12,7 +12,7 @@ project.
## General Documention
- [Tutorial](@ref flatbuffers_guide_tutorial) - select C as language
- [Tutorial](../tutorial.md) - select C as language
when scrolling down
- [FlatCC Guide](https://github.com/dvidelabs/flatcc#flatcc-flatbuffers-in-c-for-c)
- [The C Builder Interface](https://github.com/dvidelabs/flatcc/blob/master/doc/builder.md#the-builder-interface)

View File

@@ -1,18 +1,18 @@
Use in C# {#flatbuffers_guide_use_c-sharp}
Use in C\# {#flatbuffers_guide_use_c-sharp}
==============
## Before you get started
Before diving into the FlatBuffers usage in C#, it should be noted that
the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide to
the [Tutorial](../tutorial.md) page has a complete guide to
general FlatBuffers usage in all of the supported languages (including C#).
This page is designed to cover the nuances of FlatBuffers usage,
specific to C#.
You should also have read the [Building](@ref flatbuffers_guide_building)
You should also have read the [Building](../building.md)
documentation to build `flatc` and should be familiar with
[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and
[Writing a schema](@ref flatbuffers_guide_writing_schema).
[Using the schema compiler](../flatc.md) and
[Writing a schema](../schema.md).
## FlatBuffers C# code location
@@ -62,7 +62,7 @@ by running the following commands from inside the `FlatBuffers.Test` folder:
## Using the FlatBuffers C# library
*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth
*Note: See [Tutorial](../tutorial.md) for a more in-depth
example of how to use FlatBuffers in C#.*
FlatBuffers supports reading and writing binary FlatBuffers in C#.
@@ -141,7 +141,7 @@ To use it:
## Buffer verification
As mentioned in [C++ Usage](@ref flatbuffers_guide_use_cpp) buffer
As mentioned in [C++ Usage](cpp.md) buffer
accessor functions do not verify buffer offsets at run-time.
If it is necessary, you can optionally use a buffer verifier before you
access the data. This verifier will check all offsets, all sizes of

View File

@@ -1,10 +1,9 @@
Use in C++ {#flatbuffers_guide_use_cpp}
==========
# Language Guide: C++
## Before you get started
Before diving into the FlatBuffers usage in C++, it should be noted that
the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide
the [Tutorial](../tutorial.md) page has a complete guide
to general FlatBuffers usage in all of the supported languages (including C++).
This page is designed to cover the nuances of FlatBuffers usage, specific to
C++.
@@ -13,8 +12,8 @@ C++.
This page assumes you have written a FlatBuffers schema and compiled it
with the Schema Compiler. If you have not, please see
[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler)
and [Writing a schema](@ref flatbuffers_guide_writing_schema).
[Using the schema compiler](../flatc.md)
and [Writing a schema](../schema.md).
Assuming you wrote a schema, say `mygame.fbs` (though the extension doesn't
matter), you've generated a C++ header called `mygame_generated.h` using the
@@ -35,7 +34,7 @@ The test code itself is located in
[test.cpp](https://github.com/google/flatbuffers/blob/master/tests/test.cpp).
This test file is built alongside `flatc`. To review how to build the project,
please read the [Building](@ref flatbuffers_guide_building) documentation.
please read the [Building](../building.md) documentation.
To run the tests, execute `flattests` from the root `flatbuffers/` directory.
For example, on [Linux](https://en.wikipedia.org/wiki/Linux), you would simply
@@ -43,7 +42,7 @@ run: `./flattests`.
## Using the FlatBuffers C++ library
*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth
*Note: See [Tutorial](../tutorial.md) for a more in-depth
example of how to use FlatBuffers in C++.*
FlatBuffers supports both reading and writing FlatBuffers in C++.
@@ -96,7 +95,7 @@ The following attributes are supported:
Specifically, `CreateXxxDirect` functions and `Pack` functions for object
based API (see below) will use `CreateSharedString` to create strings.
## Object based API {#flatbuffers_cpp_object_based_api}
## Object based API
FlatBuffers is all about memory efficiency, which is why its base API is written
around using as little as possible of it. This does make the API clumsier
@@ -254,7 +253,7 @@ Finally, the following top-level attributes:
- `force_align`: this attribute may not be respected in the object API,
depending on the aligned of the allocator used with `new`.
# External references
## External references
An additional feature of the object API is the ability to allow you to load
multiple independent FlatBuffers, and have them refer to eachothers objects
@@ -262,7 +261,7 @@ using hashes which are then represented as typed pointers in the object API.
To make this work have a field in the objects you want to referred to which is
using the string hashing feature (see `hash` attribute in the
[schema](@ref flatbuffers_guide_writing_schema) documentation). Then you have
[schema](../schema.md) documentation). Then you have
a similar hash in the field referring to it, along with a `cpp_type`
attribute specifying the C++ type this will refer to (this can be any C++
type, and will get a `*` added).
@@ -273,7 +272,7 @@ same string (or hash).
When you call `UnPack` (or `Create`), you'll need a function that maps from
hash to the object (see `resolver_function_t` for details).
# Using different pointer types
## Using different pointer types
By default the object tree is built out of `std::unique_ptr`, but you can
influence this either globally (using the `--cpp-ptr-type` argument to
@@ -284,7 +283,7 @@ you, so you'll have to manage their lifecycles manually. To reference the
pointer type specified by the `--cpp-ptr-type` argument to `flatc` from a
flatbuffer field set the `cpp_ptr_type` attribute to `default_ptr_type`.
# Using different string type
## Using different string type
By default the object tree is built out of `std::string`, but you can
influence this either globally (using the `--cpp-str-type` argument to
@@ -556,11 +555,11 @@ recursion depth. Number of nested declarations in a schema or number of
nested json-objects is limited. By default, this depth limit set to `64`.
It is possible to override this limit with `FLATBUFFERS_MAX_PARSING_DEPTH`
definition. This definition can be helpful for testing purposes or embedded
applications. For details see [build](@ref flatbuffers_guide_building) of
applications. For details see [build](../building.md) of
CMake-based projects.
## Dependence from C-locale {#flatbuffers_locale_cpp}
The Flatbuffers [grammar](@ref flatbuffers grammar) uses ASCII
The Flatbuffers [grammar](../grammar.md) uses ASCII
character set for identifiers, alphanumeric literals, reserved words.
Internal implementation of the Flatbuffers depends from functions which
@@ -603,7 +602,7 @@ compatible with the `IEEE-754` floating-point standard.
The schema and json parser may fail if `fast-math` or `/fp:fast` mode is active.
### Support of hexadecimal and special floating-point numbers
According to the [grammar](@ref flatbuffers_grammar) `fbs` and `json` files
According to the [grammar](../grammar.md) `fbs` and `json` files
may use hexadecimal and special (`NaN`, `Inf`) floating-point literals.
The Flatbuffers uses `strtof` and `strtod` functions to parse floating-point
literals. The Flatbuffers library has a code to detect a compiler compatibility
@@ -626,7 +625,7 @@ According to the `IEEE-754`, a comparison with `NaN` always returns
an unordered result even when compared with itself. As a result, a whole
Flatbuffers object will be not equal to itself if has one or more `NaN`.
Flatbuffers scalar fields that have the default value are not actually stored
in the serialized data but are generated in code (see [Writing a schema](@ref flatbuffers_guide_writing_schema)).
in the serialized data but are generated in code (see [Writing a schema](../schema.md)).
Scalar fields with `NaN` defaults break this behavior.
If a schema has a lot of `NaN` defaults the Flatbuffers can override
the unordered comparison by the ordered: `(NaN==NaN)->true`.
@@ -636,4 +635,38 @@ Additional computations added by `FLATBUFFERS_NAN_DEFAULTS` are very cheap
if GCC or Clang used. These compilers have a compile-time implementation
of `isnan` checking which MSVC does not.
<br>
## gRPC
### Before you get started
Before diving into the FlatBuffers gRPC usage in C++, you should already be
familiar with the following:
- FlatBuffers as a serialization format
- [gRPC](http://www.grpc.io/docs/) usage
### Using the FlatBuffers gRPC C++ library
NOTE: The examples below are also in the `grpc/samples/greeter` directory.
We will illustrate usage with the following schema:
```c++ title="grpc/samples/greeter/greeter.fbs"
--8<-- "https://raw.githubusercontent.com/google/flatbuffers/refs/heads/master/grpc/samples/greeter/greeter.fbs"
```
When we run `flatc`, we pass in the `--grpc` option and generage an additional
`greeter.grpc.fb.h` and `greeter.grpc.fb.cc`.
Example server code looks like this:
```c++ title="grpc/samples/greeter/server.cpp"
--8<-- "https://raw.githubusercontent.com/google/flatbuffers/refs/heads/master/grpc/samples/greeter/server.cpp"
```
Example client code looks like this:
```c++ title="grpc/samples/greeter/client.cpp"
--8<-- "https://raw.githubusercontent.com/google/flatbuffers/refs/heads/master/grpc/samples/greeter/client.cpp"
```

View File

@@ -4,15 +4,15 @@ Use in Dart {#flatbuffers_guide_use_dart}
## Before you get started
Before diving into the FlatBuffers usage in Dart, it should be noted that
the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide
the [Tutorial](../tutorial.md) page has a complete guide
to general FlatBuffers usage in all of the supported languages (including Dart).
This page is designed to cover the nuances of FlatBuffers usage, specific to
Dart.
You should also have read the [Building](@ref flatbuffers_guide_building)
You should also have read the [Building](../building.md)
documentation to build `flatc` and should be familiar with
[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and
[Writing a schema](@ref flatbuffers_guide_writing_schema).
[Using the schema compiler](../flatc.md) and
[Writing a schema](../schema.md).
## FlatBuffers Dart library code location
@@ -34,7 +34,7 @@ to be installed.*
## Using the FlatBuffers Dart library
*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth
*Note: See [Tutorial](../tutorial.md) for a more in-depth
example of how to use FlatBuffers in Dart.*
FlatBuffers supports reading and writing binary FlatBuffers in Dart.

View File

@@ -4,15 +4,15 @@ Use in Go {#flatbuffers_guide_use_go}
## Before you get started
Before diving into the FlatBuffers usage in Go, it should be noted that
the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide
the [Tutorial](../tutorial.md) page has a complete guide
to general FlatBuffers usage in all of the supported languages (including Go).
This page is designed to cover the nuances of FlatBuffers usage, specific to
Go.
You should also have read the [Building](@ref flatbuffers_guide_building)
You should also have read the [Building](../building.md)
documentation to build `flatc` and should be familiar with
[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and
[Writing a schema](@ref flatbuffers_guide_writing_schema).
[Using the schema compiler](../flatc.md) and
[Writing a schema](../schema.md).
## FlatBuffers Go library code location
@@ -34,7 +34,7 @@ be installed.*
## Using the FlatBuffers Go library
*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth
*Note: See [Tutorial](../tutorial.md) for a more in-depth
example of how to use FlatBuffers in Go.*
FlatBuffers supports reading and writing binary FlatBuffers in Go.

View File

@@ -4,15 +4,15 @@ Use in Java {#flatbuffers_guide_use_java}
## Before you get started
Before diving into the FlatBuffers usage in Java, it should be noted that
the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide to
the [Tutorial](../tutorial.md) page has a complete guide to
general FlatBuffers usage in all of the supported languages (including Java).
This page is designed to cover the nuances of FlatBuffers usage,
specific to Java.
You should also have read the [Building](@ref flatbuffers_guide_building)
You should also have read the [Building](../building.md)
documentation to build `flatc` and should be familiar with
[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and
[Writing a schema](@ref flatbuffers_guide_writing_schema).
[Using the schema compiler](../flatc.md) and
[Writing a schema](../schema.md).
## FlatBuffers Java code location
@@ -38,7 +38,7 @@ is installed.*
## Using the FlatBuffers Java library
*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth
*Note: See [Tutorial](../tutorial.md) for a more in-depth
example of how to use FlatBuffers in Java.*
FlatBuffers supports reading and writing binary FlatBuffers in Java.

View File

@@ -4,15 +4,15 @@ Use in JavaScript {#flatbuffers_guide_use_javascript}
## Before you get started
Before diving into the FlatBuffers usage in JavaScript, it should be noted that
the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide to
the [Tutorial](../tutorial.md) page has a complete guide to
general FlatBuffers usage in all of the supported languages
(including JavaScript). This page is specifically designed to cover the nuances
of FlatBuffers usage in JavaScript.
You should also have read the [Building](@ref flatbuffers_guide_building)
You should also have read the [Building](../building.md)
documentation to build `flatc` and should be familiar with
[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and
[Writing a schema](@ref flatbuffers_guide_writing_schema).
[Using the schema compiler](../flatc.md) and
[Writing a schema](../schema.md).
## FlatBuffers JavaScript library code location
@@ -25,13 +25,13 @@ folder as the source.
## Using the FlatBuffers JavaScript library
*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth
*Note: See [Tutorial](../tutorial.md) for a more in-depth
example of how to use FlatBuffers.*
Due to the complexity related with large amounts of JS flavors and module types,
native JS support has been replaced in 2.0 by transpilation from TypeScript.
Please look at [TypeScript usage](@ref flatbuffers_guide_use_typescript) and
Please look at [TypeScript usage](typescript.md) and
transpile your sources to desired JS flavor. The minimal steps to get up and
running with JS are:

View File

@@ -4,15 +4,15 @@ Use in Kotlin {#flatbuffers_guide_use_kotlin}
## Before you get started
Before diving into the FlatBuffers usage in Kotlin, it should be noted that
the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide to
the [Tutorial](../tutorial.md) page has a complete guide to
general FlatBuffers usage in all of the supported languages (including K).
This page is designed to cover the nuances of FlatBuffers usage, specific to Kotlin.
You should also have read the [Building](@ref flatbuffers_guide_building)
You should also have read the [Building](../building.md)
documentation to build `flatc` and should be familiar with
[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and
[Writing a schema](@ref flatbuffers_guide_writing_schema).
[Using the schema compiler](../flatc.md) and
[Writing a schema](../schema.md).
## Kotlin and FlatBuffers Java code location
@@ -35,7 +35,7 @@ flatbuffers/blob/master/tests/KotlinTest.sh) shell script.
## Using the FlatBuffers Kotlin library
*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth
*Note: See [Tutorial](../tutorial.md) for a more in-depth
example of how to use FlatBuffers in Kotlin.*
FlatBuffers supports reading and writing binary FlatBuffers in Kotlin.

View File

@@ -4,15 +4,15 @@ Use in Lobster {#flatbuffers_guide_use_lobster}
## Before you get started
Before diving into the FlatBuffers usage in Lobster, it should be noted that the
[Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide to general
[Tutorial](../tutorial.md) page has a complete guide to general
FlatBuffers usage in all of the supported languages (including Lobster). This
page is designed to cover the nuances of FlatBuffers usage, specific to
Lobster.
You should also have read the [Building](@ref flatbuffers_guide_building)
You should also have read the [Building](../building.md)
documentation to build `flatc` and should be familiar with
[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and
[Writing a schema](@ref flatbuffers_guide_writing_schema).
[Using the schema compiler](../flatc.md) and
[Writing a schema](../schema.md).
## FlatBuffers Lobster library code location
@@ -34,7 +34,7 @@ platform.
## Using the FlatBuffers Lobster library
*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth
*Note: See [Tutorial](../tutorial.md) for a more in-depth
example of how to use FlatBuffers in Lobster.*
There is support for both reading and writing FlatBuffers in Lobster.

View File

@@ -4,15 +4,15 @@ Use in Lua {#flatbuffers_guide_use_lua}
## Before you get started
Before diving into the FlatBuffers usage in Lua, it should be noted that the
[Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide to general
[Tutorial](../tutorial.md) page has a complete guide to general
FlatBuffers usage in all of the supported languages (including Lua). This
page is designed to cover the nuances of FlatBuffers usage, specific to
Lua.
You should also have read the [Building](@ref flatbuffers_guide_building)
You should also have read the [Building](../building.md)
documentation to build `flatc` and should be familiar with
[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and
[Writing a schema](@ref flatbuffers_guide_writing_schema).
[Using the schema compiler](../flatc.md) and
[Writing a schema](../schema.md).
## FlatBuffers Lua library code location
@@ -34,7 +34,7 @@ blob/master/tests/LuaTest.sh) shell script.
## Using the FlatBuffers Lua library
*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth
*Note: See [Tutorial](../tutorial.md) for a more in-depth
example of how to use FlatBuffers in Lua.*
There is support for both reading and writing FlatBuffers in Lua.

View File

@@ -4,15 +4,15 @@ Use in PHP {#flatbuffers_guide_use_php}
## Before you get started
Before diving into the FlatBuffers usage in PHP, it should be noted that
the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide to
the [Tutorial](../tutorial.md) page has a complete guide to
general FlatBuffers usage in all of the supported languages
(including PHP). This page is specifically designed to cover the nuances of
FlatBuffers usage in PHP.
You should also have read the [Building](@ref flatbuffers_guide_building)
You should also have read the [Building](../building.md)
documentation to build `flatc` and should be familiar with
[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and
[Writing a schema](@ref flatbuffers_guide_writing_schema).
[Using the schema compiler](../flatc.md) and
[Writing a schema](../schema.md).
## FlatBuffers PHP library code location
@@ -33,7 +33,7 @@ You can run the test with `php phpTest.php` from the command line.
## Using theFlatBuffers PHP library
*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth
*Note: See [Tutorial](../tutorial.md) for a more in-depth
example of how to use FlatBuffers in PHP.*
FlatBuffers supports both reading and writing FlatBuffers in PHP.

View File

@@ -4,15 +4,15 @@ Use in Python {#flatbuffers_guide_use_python}
## Before you get started
Before diving into the FlatBuffers usage in Python, it should be noted that the
[Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide to general
[Tutorial](../tutorial.md) page has a complete guide to general
FlatBuffers usage in all of the supported languages (including Python). This
page is designed to cover the nuances of FlatBuffers usage, specific to
Python.
You should also have read the [Building](@ref flatbuffers_guide_building)
You should also have read the [Building](../building.md)
documentation to build `flatc` and should be familiar with
[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and
[Writing a schema](@ref flatbuffers_guide_writing_schema).
[Using the schema compiler](../flatc.md) and
[Writing a schema](../schema.md).
## FlatBuffers Python library code location
@@ -35,7 +35,7 @@ installed.*
## Using the FlatBuffers Python library
*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth
*Note: See [Tutorial](../tutorial.md) for a more in-depth
example of how to use FlatBuffers in Python.*
There is support for both reading and writing FlatBuffers in Python.

View File

@@ -4,7 +4,7 @@ Use in Rust {#flatbuffers_guide_use_rust}
## Before you get started
Before diving into the FlatBuffers usage in Rust, it should be noted that
the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide
the [Tutorial](../tutorial.md) page has a complete guide
to general FlatBuffers usage in all of the supported languages (including Rust).
This page is designed to cover the nuances of FlatBuffers usage, specific to
Rust.
@@ -13,8 +13,8 @@ Rust.
This page assumes you have written a FlatBuffers schema and compiled it
with the Schema Compiler. If you have not, please see
[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler)
and [Writing a schema](@ref flatbuffers_guide_writing_schema).
[Using the schema compiler](../flatc.md)
and [Writing a schema](../schema.md).
Assuming you wrote a schema, say `mygame.fbs` (though the extension doesn't
matter), you've generated a Rust file called `mygame_generated.rs` using the
@@ -36,7 +36,7 @@ The test code itself is located in
[integration_test.rs](https://github.com/google/flatbuffers/blob/master/tests/rust_usage_test/tests/integration_test.rs)
This test file requires `flatc` to be present. To review how to build the project,
please read the [Building](@ref flatbuffers_guide_building) documentation.
please read the [Building](../building.md) documentation.
To run the tests, execute `RustTest.sh` from the `flatbuffers/tests` directory.
For example, on [Linux](https://en.wikipedia.org/wiki/Linux), you would simply
@@ -47,7 +47,7 @@ be installed.*
## Using the FlatBuffers Rust library
*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth
*Note: See [Tutorial](../tutorial.md) for a more in-depth
example of how to use FlatBuffers in Rust.*
FlatBuffers supports both reading and writing FlatBuffers in Rust.

View File

@@ -4,15 +4,15 @@ Use in Swift {#flatbuffers_guide_use_swift}
## Before you get started
Before diving into the FlatBuffers usage in Swift, it should be noted that
the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide
the [Tutorial](../tutorial.md) page has a complete guide
to general FlatBuffers usage in all of the supported languages (including Swift).
This page is designed to cover the nuances of FlatBuffers usage, specific to
Swift.
You should also have read the [Building](@ref flatbuffers_guide_building)
You should also have read the [Building](../building.md)
documentation to build `flatc` and should be familiar with
[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and
[Writing a schema](@ref flatbuffers_guide_writing_schema).
[Using the schema compiler](../flatc.md) and
[Writing a schema](../schema.md).
## FlatBuffers Swift library code location
@@ -32,7 +32,7 @@ be installed.*
## Using the FlatBuffers Swift library
*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth
*Note: See [Tutorial](../tutorial.md) for a more in-depth
example of how to use FlatBuffers in Swift.*
FlatBuffers supports reading and writing binary FlatBuffers in Swift.

View File

@@ -4,15 +4,15 @@ Use in TypeScript {#flatbuffers_guide_use_typescript}
## Before you get started
Before diving into the FlatBuffers usage in TypeScript, it should be noted that
the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide to
the [Tutorial](../tutorial.md) page has a complete guide to
general FlatBuffers usage in all of the supported languages
(including TypeScript). This page is specifically designed to cover the nuances
of FlatBuffers usage in TypeScript.
You should also have read the [Building](@ref flatbuffers_guide_building)
You should also have read the [Building](../building.md)
documentation to build `flatc` and should be familiar with
[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and
[Writing a schema](@ref flatbuffers_guide_writing_schema).
[Using the schema compiler](../flatc.md) and
[Writing a schema](../schema.md).
## FlatBuffers TypeScript library code location
@@ -28,7 +28,7 @@ flatbuffers/blob/master/tests/TypeScriptTest.py) Python3 script.
## Using the FlatBuffers TypeScript library
*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth
*Note: See [Tutorial](../tutorial.md) for a more in-depth
example of how to use FlatBuffers in TypeScript.*
FlatBuffers supports both reading and writing FlatBuffers in TypeScript.

View File

@@ -0,0 +1,90 @@
# Quick Start
This will quickly go over the parts of using FlatBuffers to serialize some data.
See the [Tutorial](tutorial.md) for a more in depth guide.
1. **Build the compiler for FlatBuffers ([`flatc`](flatc.md))**
```sh
cmake -G "Unix Makefiles"
make -j
```
2. **Define your FlatBuffer [schema](schema.md) (`.fbs`)**
```c title="monster.fbs" linenums="1"
table Monster {
name:string;
health:int;
}
root_type Monster;
```
See [monster.fbs](https://github.com/google/flatbuffers/blob/master/samples/monster.fbs)
for an complete example.
3. **Generate code for your language(s)**
Use the `flatc` compiler to take your schema and generate language-specific
code:
```sh
./flatc --cpp --rust mosnter.fbs
```
Which generates `monster_generated.h` and `monster_generated.rs` files.
4. **Serialize data**
Use the generated code files, as well as the `FlatBufferBuilder` to construct
your serialized buffer.
```c++ title="my_monster_factory.cc" linenums="1"
#include "flatbuffers.h"
#include "monster_generated.h"
int main() {
// Used to build the flatbuffer
FlatBufferBuilder builder;
// Auto-generated function emitted from `flatc` and the input
// `monster.fbs` schema.
auto monster = CreateMonsterDirect(builder, "Abominable Snowman", 100);
// Finalize the buffer.
builder.Finish(monster);
}
```
See complete [C++ Example](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.cpp#L24-L56).
5. **Transmit/Store the serialized FlatBuffer**
Use your serialized buffer however you want. Send it to someone, save if for
later, etc...
```c++ title="my_monster_factory.cc" linenums="13"
// Get a pointer to the flatbuffer.
const uint8_t* flatbuffer = builder.GetBufferPointer();
```
6. **Read the data**
Use the generated accessors to read the data from the serialized buffer.
It doesn't need to be the same language, or even schema version (see
[Evolving](evolution.md)), FlatBuffers ensures the data is readable across
languages and schema versions.
```c++ title="my_monster_factory.cc" linenums="15"
// Get a view of the root monster from the flatbuffer.
const Monster snowman = GetMonster(flatbuffer);
// Access the monster's fields directly.
ASSERT_EQ(snowman->name(), "Abominable Snowman");
ASSERT_EQ(snowman->health(), 100);
```
See [`Rust` examples](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.rs#L92-L106)
for reading the data written by `C++`.

645
docs/source/schema.md Normal file
View File

@@ -0,0 +1,645 @@
# Schema
The syntax of the schema language (aka IDL,
[Interface Definition Language](https://en.wikipedia.org/wiki/Interface_description_language))
should look quite familiar to users of any of the C family of languages, and
also to users of other IDLs. Let's look at an example first:
```c title="monster.fbs" linenums="1"
// example IDL file
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;
```
## Tables
Tables are the main way of defining objects in FlatBuffers.
```c title="monster.fbs - Example Table" linenums="17"
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;
}
```
They consist of a name (here `Monster`) and a list of [fields](#fields). This
field list can be appended to (and deprecated from) while still maintaining
compatibility.
### Fields
Table fields have a name identifier, a [type](#types), optional default value,
optional [attributes](#attributes) and ends with a `;`. See the
[grammar](grammar.md) for full details.
```ebnf
field_decl = ident `:` type [ `=` scalar ] metadata `;`
```
Fields do not have to appear in the wire representation, and you can choose to
omit fields when constructing an object. You have the flexibility to add fields
without fear of bloating your data. This design is also FlatBuffer's mechanism
for forward and backwards compatibility.
There are three, mutually exclusive, reactions to the non-presence of a table's
field in the binary data.
#### 1. Default
Default value fields with return the default value as defined in the schema. If
the default value is not specified in the schema, it will be `0` for scalar
types, or `null` for other types.
```c++
mana:short = 150;
hp:short;
inventory:[ubyte];
```
Here `mana` would default to the value `150`, `hp` to value `0`, and `inventory`
to `null`, if those fields are not set.
Only scalar values can have explicit defaults, non-scalar fields (strings,
vectors, tables) are `null` when not present.
This is the normal mode that fields will take.
??? danger "Don't change Default values"
You generally do not want to change default values after they're initially
defined. Fields that have the default value are not actually stored in the
serialized data (see also Gotchas below). Values explicitly written by code
generated by the old schema old version, if they happen to be the default, will
be read as a different value by code generated with the new schema. This is
slightly less bad when converting an optional scalar into a default valued
scalar since non-presence would not be overloaded with a previous default value.
There are situations, however, where this may be desirable, especially if you
can ensure a simultaneous rebuild of all code.
#### 2. Optional
Optional value fields will return some form of `null` in the language generated.
=== "C++"
```c++
std::optional<T> field;
```
For optional scalars, just set the field default value to `null`. If the
producer of the buffer does not explicitly set that field, it will be marked
`null`.
```c++
hp:short = null;
```
!!! note
Not every languages support scalar defaults yet
#### 3. Required
Required valued fields will cause an error if they are not set. The FlatBuffers
verifier would consider the whole buffer invalid.
This is enabled by the [`required` attribute](#required) on the field.
```
hp:short (required)
```
You cannot have `required` set with an explicit default value, it will result in
a compiler error.
## Structs
Similar to a table, `structs` consist of fields are required (so no defaults
either), and fields may not be added or be deprecated.
```c title="monster.fbs - Example Struct" linenums="11"
struct Vec3 {
x:float;
y:float;
z:float;
}
```
Structs may only contain scalars or other structs. Use this for simple objects
where you are very sure no changes will ever be made (as quite clear in the
example `Vec3`). Structs use less memory than tables and are even faster to
access (they are always stored in-line in their parent object, and use no
virtual table).
### Arrays
Arrays are a convenience short-hand for a fixed-length collection of elements.
Arrays allow the following syntax, while maintaining binary equivalency.
<div class="grid cards" markdown>
- **Normal Syntax**
===
```c++
struct Vec3 {
x:float;
y:float;
z:float;
}
```
- **Array Syntax**
===
```c++
struct Vec3 {
v:[float:3];
}
```
</div>
Arrays are currently only supported in a `struct`.
## Types
The following are the built-in types that can be used in FlatBuffers.
### Scalars
The standard assortment of fixed sized scalars are available. There are no
variable sized integers (e.g., `varints`).
| Size | Signed | Unsigned | Floating Point |
| ------ | ----------------- | ------------------- | -------------------- |
| 8-bit | `byte`, `bool` | `ubyte` (`uint8`) | |
| 16-bit | `short` (`int16`) | `ushort` (`uint16`) |
| 32-bit | `int` (`int32`) | `uint` (`uint32`) | `float` (`float32`) |
| 64-bit | `long` (`int64`) | `ulong` (`uint64`) | `double` (`float64`) |
The type names in parentheses are alias names such that for example `uint8` can
be used in place of `ubyte`, and `int32` can be used in place of `int` without
affecting code generation.
### Non-scalars
#### Vectors
Vector of any other type (denoted with `[type]`).
```c++
inventory:[ubyte];
```
!!! note "Nesting vectors"
Nesting vectors is not supported, instead you can wrap the inner vector with
a table.
```
table nest{
a:[ubyte]
}
table monster {
a:[nest]
}
```
#### Strings
Strings (indicated by `string`) are zero-terminated strings, prefixed by their
length. Strings may only hold UTF-8 or 7-bit ASCII. For other text encodings or
general binary data use vectors (`[byte]` or `[ubyte]`) instead.
```c++
name:string;
```
## Enums
Define a sequence of named constants, each with a given value, or increasing by
one from the previous one. The default first value is `0`. As you can see in the
enum declaration, you specify the underlying integral type of the enum with `:`
(in this case `byte`), which then determines the type of any fields declared
with this enum type.
Only integer types are allowed, i.e. `byte`, `ubyte`, `short` `ushort`, `int`,
`uint`, `long` and `ulong`.
Typically, enum values should only ever be added, never removed (there is no
deprecation for enums). This requires code to handle forwards compatibility
itself, by handling unknown enum values.
## Unions
Unions share a lot of properties with enums, but instead of new names for
constants, you use names of tables. You can then declare a union field, which
can hold a reference to any of those types, and additionally a field with the
suffix `_type` is generated that holds the corresponding enum value, allowing
you to know which type to cast to at runtime.
It's possible to give an alias name to a type union. This way a type can even be
used to mean different things depending on the name used:
```txt
table PointPosition { x:uint; y:uint; }
table MarkerPosition {}
union Position {
Start:MarkerPosition,
Point:PointPosition,
Finish:MarkerPosition
}
```
Unions contain a special `NONE` marker to denote that no value is stored so that
name cannot be used as an alias.
Unions are a good way to be able to send multiple message types as a FlatBuffer.
Note that because a union field is really two fields, it must always be part of
a table, it cannot be the root of a FlatBuffer by itself.
If you have a need to distinguish between different FlatBuffers in a more
open-ended way, for example for use as files, see the file identification
feature below.
There is an experimental support only in C++ for a vector of unions (and types).
In the example IDL file above, use [Any] to add a vector of Any to Monster
table. There is also experimental support for other types besides tables in
unions, in particular structs and strings. There's no direct support for scalars
in unions, but they can be wrapped in a struct at no space cost.
## Namespaces
These will generate the corresponding namespace in C++ for all helper code, and
packages in Java. You can use `.` to specify nested namespaces / packages.
## Includes
You can include other schemas files in your current one, e.g.:
```txt
include "mydefinitions.fbs";
```
This makes it easier to refer to types defined elsewhere. `include`
automatically ensures each file is parsed just once, even when referred to more
than once.
When using the `flatc` compiler to generate code for schema definitions, only
definitions in the current file will be generated, not those from the included
files (those you still generate separately).
## Root type
This declares what you consider to be the root table of the serialized data.
This is particularly important for parsing JSON data, which doesn't include
object type information.
## File identification and extension
Typically, a FlatBuffer binary buffer is not self-describing, i.e. it needs you
to know its schema to parse it correctly. But if you want to use a FlatBuffer as
a file format, it would be convenient to be able to have a "magic number" in
there, like most file formats have, to be able to do a sanity check to see if
you're reading the kind of file you're expecting.
Now, you can always prefix a FlatBuffer with your own file header, but
FlatBuffers has a built-in way to add an identifier to a FlatBuffer that takes
up minimal space, and keeps the buffer compatible with buffers that don't have
such an identifier.
You can specify in a schema, similar to `root_type`, that you intend for this
type of FlatBuffer to be used as a file format:
```txt
file_identifier "MYFI";
```
Identifiers must always be exactly 4 characters long. These 4 characters will
end up as bytes at offsets 4-7 (inclusive) in the buffer.
For any schema that has such an identifier, `flatc` will automatically add the
identifier to any binaries it generates (with `-b`), and generated calls like
`FinishMonsterBuffer` also add the identifier. If you have specified an
identifier and wish to generate a buffer without one, you can always still do so
by calling `FlatBufferBuilder::Finish` explicitly.
After loading a buffer, you can use a call like `MonsterBufferHasIdentifier` to
check if the identifier is present.
Note that this is best for open-ended uses such as files. If you simply wanted
to send one of a set of possible messages over a network for example, you'd be
better off with a union.
Additionally, by default `flatc` will output binary files as `.bin`. This
declaration in the schema will change that to whatever you want:
```txt
file_extension "ext";
```
## RPC interface declarations
You can declare RPC calls in a schema, that define a set of functions that take
a FlatBuffer as an argument (the request) and return a FlatBuffer as the
response (both of which must be table types):
```txt
rpc_service MonsterStorage {
Store(Monster):StoreResponse;
Retrieve(MonsterId):Monster;
}
```
What code this produces and how it is used depends on language and RPC system
used, there is preliminary support for GRPC through the `--grpc` code generator,
see `grpc/tests` for an example.
## Comments & documentation
May be written as in most C-based languages. Additionally, a triple comment
(`///`) on a line by itself signals that a comment is documentation for whatever
is declared on the line after it (table/struct/field/enum/union/element), and
the comment is output in the corresponding C++ code. Multiple such lines per
item are allowed.
## Attributes
Attributes may be attached to a declaration, behind a field/enum value, or after
the name of a table/struct/enum/union. These may either have a value or not.
Some attributes like `deprecated` are understood by the compiler; user defined
ones need to be declared with the attribute declaration (like `priority` in the
example above), and are available to query if you parse the schema at runtime.
This is useful if you write your own code generators/editors etc., and you wish
to add additional information specific to your tool (such as a help text).
Current understood attributes:
- `id: n` (on a table field): manually set the field identifier to `n`. If you
use this attribute, you must use it on ALL fields of this table, and the
numbers must be a contiguous range from 0 onwards. Additionally, since a union
type effectively adds two fields, its id must be that of the second field (the
first field is the type field and not explicitly declared in the schema). For
example, if the last field before the union field had id 6, the union field
should have id 8, and the unions type field will implicitly be 7. IDs allow
the fields to be placed in any order in the schema. When a new field is added
to the schema it must use the next available ID.
- `deprecated` (on a field): do not generate accessors for this field anymore,
code should stop using this data. Old data may still contain this field, but
it won't be accessible anymore by newer code. Note that if you deprecate a
field that was previous required, old code may fail to validate new data (when
using the optional verifier).
### `required`
- `required` (on a non-scalar table field): this field must always be set. By
default, fields do not need to be present in the binary. This is desirable, as
it helps with forwards/backwards compatibility, and flexibility of data
structures. By specifying this attribute, you make non- presence in an error
for both reader and writer. The reading code may access the field directly,
without checking for null. If the constructing code does not initialize this
field, they will get an assert, and also the verifier will fail on buffers
that have missing required fields. Both adding and removing this attribute may
be forwards/backwards incompatible as readers will be unable read old or new
data, respectively, unless the data happens to always have the field set.
- `force_align: size` (on a struct): force the alignment of this struct to be
something higher than what it is naturally aligned to. Causes these structs to
be aligned to that amount inside a buffer, IF that buffer is allocated with
that alignment (which is not necessarily the case for buffers accessed
directly inside a `FlatBufferBuilder`). Note: currently not guaranteed to have
an effect when used with `--object-api`, since that may allocate objects at
alignments less than what you specify with `force_align`.
- `force_align: size` (on a vector): force the alignment of this vector to be
something different than what the element size would normally dictate. Note:
Now only work for generated C++ code.
- `bit_flags` (on an unsigned enum): the values of this field indicate bits,
meaning that any unsigned value N specified in the schema will end up
representing 1<<N, or if you don't specify values at all, you'll get the
sequence 1, 2, 4, 8, ...
- `nested_flatbuffer: "table_name"` (on a field): this indicates that the field
(which must be a vector of ubyte) contains flatbuffer data, for which the root
type is given by `table_name`. The generated code will then produce a
convenient accessor for the nested FlatBuffer.
- `flexbuffer` (on a field): this indicates that the field (which must be a
vector of ubyte) contains flexbuffer data. The generated code will then
produce a convenient accessor for the FlexBuffer root.
- `key` (on a field): this field is meant to be used as a key when sorting a
vector of the type of table it sits in. Can be used for in-place binary
search.
- `hash` (on a field). This is an (un)signed 32/64 bit integer field, whose
value during JSON parsing is allowed to be a string, which will then be stored
as its hash. The value of attribute is the hashing algorithm to use, one of
`fnv1_32` `fnv1_64` `fnv1a_32` `fnv1a_64`.
- `original_order` (on a table): since elements in a table do not need to be
stored in any particular order, they are often optimized for space by sorting
them to size. This attribute stops that from happening. There should generally
not be any reason to use this flag.
- 'native*\*'. Several attributes have been added to support the C++ object
Based API. All such attributes are prefixed with the term "native*".
## JSON Parsing
The same parser that parses the schema declarations above is also able to parse
JSON objects that conform to this schema. So, unlike other JSON parsers, this
parser is strongly typed, and parses directly into a FlatBuffer (see the
compiler documentation on how to do this from the command line, or the C++
documentation on how to do this at runtime).
Besides needing a schema, there are a few other changes to how it parses JSON:
- It accepts field names with and without quotes, like many JSON parsers already
do. It outputs them without quotes as well, though can be made to output them
using the `strict_json` flag.
- If a field has an enum type, the parser will recognize symbolic enum values
(with or without quotes) instead of numbers, e.g. `field: EnumVal`. If a field
is of integral type, you can still use symbolic names, but values need to be
prefixed with their type and need to be quoted, e.g. `field: "Enum.EnumVal"`.
For enums representing flags, you may place multiple inside a string separated
by spaces to OR them, e.g. `field: "EnumVal1 EnumVal2"` or
`field: "Enum.EnumVal1 Enum.EnumVal2"`.
- Similarly, for unions, these need to specified with two fields much like you
do when serializing from code. E.g. for a field `foo`, you must add a field
`foo_type: FooOne` right before the `foo` field, where `FooOne` would be the
table out of the union you want to use.
- A field that has the value `null` (e.g. `field: null`) is intended to have the
default value for that field (thus has the same effect as if that field wasn't
specified at all).
- It has some built in conversion functions, so you can write for example
`rad(180)` where ever you'd normally write `3.14159`. Currently supports the
following functions: `rad`, `deg`, `cos`, `sin`, `tan`, `acos`, `asin`,
`atan`.
When parsing JSON, it recognizes the following escape codes in strings:
- `\n` - linefeed.
- `\t` - tab.
- `\r` - carriage return.
- `\b` - backspace.
- `\f` - form feed.
- `\"` - double quote.
- `\\` - backslash.
- `\/` - forward slash.
- `\uXXXX` - 16-bit unicode code point, converted to the equivalent UTF-8
representation.
- `\xXX` - 8-bit binary hexadecimal number XX. This is the only one that is not
in the JSON spec (see http://json.org/), but is needed to be able to encode
arbitrary binary in strings to text and back without losing information (e.g.
the byte 0xFF can't be represented in standard JSON).
It also generates these escape codes back again when generating JSON from a
binary representation.
When parsing numbers, the parser is more flexible than JSON. A format of numeric
literals is more close to the C/C++. According to the
[grammar](grammar.md), it accepts the following numerical literals:
- An integer literal can have any number of leading zero `0` digits. Unlike
C/C++, the parser ignores a leading zero, not interpreting it as the beginning
of the octal number. The numbers `[081, -00094]` are equal to `[81, -94]`
decimal integers.
- The parser accepts unsigned and signed hexadecimal integer numbers. For
example: `[0x123, +0x45, -0x67]` are equal to `[291, 69, -103]` decimals.
- The format of float-point numbers is fully compatible with C/C++ format. If a
modern C++ compiler is used the parser accepts hexadecimal and special
floating-point literals as well:
`[-1.0, 2., .3e0, 3.e4, 0x21.34p-5, -inf, nan]`.
The following conventions for floating-point numbers are used:
- The exponent suffix of hexadecimal floating-point number is mandatory.
- Parsed `NaN` converted to unsigned IEEE-754 `quiet-NaN` value.
Extended floating-point support was tested with:
- x64 Windows: `MSVC2015` and higher.
- x64 Linux: `LLVM 6.0`, `GCC 4.9` and higher.
- For compatibility with a JSON lint tool all numeric literals of scalar fields
can be wrapped to quoted string:
`"1", "2.0", "0x48A", "0x0C.0Ep-1", "-inf", "true"`.
## Guidelines
### Efficiency
FlatBuffers is all about efficiency, but to realize that efficiency you require
an efficient schema. There are usually multiple choices on how to represent data
that have vastly different size characteristics.
It is very common nowadays to represent any kind of data as dictionaries (as in
e.g. JSON), because of its flexibility and extensibility. While it is possible
to emulate this in FlatBuffers (as a vector of tables with key and value(s)),
this is a bad match for a strongly typed system like FlatBuffers, leading to
relatively large binaries. FlatBuffer tables are more flexible than
classes/structs in most systems, since having a large number of fields only few
of which are actually used is still efficient. You should thus try to organize
your data as much as possible such that you can use tables where you might be
tempted to use a dictionary.
Similarly, strings as values should only be used when they are truly open-ended.
If you can, always use an enum instead.
FlatBuffers doesn't have inheritance, so the way to represent a set of related
data structures is a union. Unions do have a cost however, so an alternative to
a union is to have a single table that has all the fields of all the data
structures you are trying to represent, if they are relatively similar / share
many fields. Again, this is efficient because non-present fields are cheap.
FlatBuffers supports the full range of integer sizes, so try to pick the
smallest size needed, rather than defaulting to int/long.
Remember that you can share data (refer to the same string/table within a
buffer), so factoring out repeating data into its own data structure may be
worth it.
### Style guide
Identifiers in a schema are meant to translate to many different programming
languages, so using the style of your "main" language is generally a bad idea.
For this reason, below is a suggested style guide to adhere to, to keep schemas
consistent for interoperation regardless of the target language.
Where possible, the code generators for specific languages will generate
identifiers that adhere to the language style, based on the schema identifiers.
- Table, struct, enum and rpc names (types): UpperCamelCase.
- Table and struct field names: snake_case. This is translated to lowerCamelCase
automatically for some languages, e.g. Java.
- Enum values: UpperCamelCase.
- namespaces: UpperCamelCase.
Formatting (this is less important, but still worth adhering to):
- Opening brace: on the same line as the start of the declaration.
- Spacing: Indent by 2 spaces. None around `:` for types, on both sides for `=`.
For an example, see the schema at the top of this file.
## Gotchas
### Testing whether a field is present in a table
Most serialization formats (e.g. JSON or Protocol Buffers) make it very explicit
in the format whether a field is present in an object or not, allowing you to
use this as "extra" information.
FlatBuffers will not write fields that are equal to their default value,
sometimes resulting in significant space savings. However, this also means we
cannot disambiguate the meaning of non-presence as "written default value" or
"not written at all". This only applies to scalar fields since only they support
default values. Unless otherwise specified, their default is 0.
If you care about the presence of scalars, most languages support "optional
scalars." You can set `null` as the default value in the schema. `null` is a
value that's outside of all types, so we will always write if `add_field` is
called. The generated field accessor should use the local language's canonical
optional type.
Some `FlatBufferBuilder` implementations have an option called `force_defaults`
that circumvents this "not writing defaults" behavior you can then use
`IsFieldPresent` to query presence. / Another option that works in all languages
is to wrap a scalar field in a struct. This way it will return null if it is not
present. This will be slightly less ergonomic but structs don't take up any more
space than the scalar they represent.

View File

@@ -1,396 +0,0 @@
body,
#projectname,
table,
div,
p,
dl,
.title,
.tabs,
.tabs2,
.tabs3,
#nav-tree .label {
font-family: roboto, sans-serif;
}
#commonprojectlogo {
padding: 5px 0px 5px 15px;
}
#projectname {
color: #00bcd4;
font-size: 280%;
padding: 15px 0px;
font-weight: 300;
}
#titlearea {
border-bottom: 2px solid #e5e5e5;
}
.title {
color: #212121;
font: 300 34px/40px Roboto,sans-serif;
}
#nav-tree {
background-color: #fff;
}
#navrow1, #navrow2 {
border-bottom: 2px solid #e7e7e7;
}
.tabs, .tabs2, .tabs3 {
font-size: 14px;
}
.tabs,
.tabs2,
.tabs3,
.tablist li,
.tablist li.current a {
background-image: none;
}
.tablist {
list-style: none;
}
.tablist li, .tablist li p {
margin: 0;
}
.tablist li a,
.tablist li.current a {
color: #757575;
text-shadow: none;
}
.tablist li.current a {
background: #00bcd4;
color: #fff;
}
.tablist a {
background-image: none;
border-right: 2px solid #e5e5e5;
font-weight: normal;
}
.tablist a:hover,
.tablist li.current a:hover {
background-image: none;
text-decoration: underline;
text-shadow: none;
}
.tablist a:hover {
color: #00bcd4;
}
.tablist li.current a:hover {
color: #fff;
}
div.header {
background-color: #f7f7f7;
background-image: none;
border-bottom: none;
}
#MSearchBox {
border: 1px solid #ccc;
border-radius: 5px;
display: inline-block;
height: 20px;
right: 10px;
}
#MSearchBox .left,
#MSearchBox .right,
#MSearchField {
background: none;
}
a.SelectItem:hover {
background-color: #00bcd4;
}
#nav-tree {
background-image: none;
}
#nav-tree .selected {
background-image: none;
text-shadow: none;
background-color: #f7f7f7;
}
#nav-tree a {
color: #212121;
}
#nav-tree .selected a {
color: #0288d1;
}
#nav-tree .item:hover {
background-color: #f7f7f7;
}
#nav-tree .item:hover a {
color: #0288d1;
}
#nav-tree .label {
font-size: 13px;
}
#nav-sync {
display: none;
}
.ui-resizable-e {
background: #ebebeb;
border-left: 1px solid #ddd;
border-right: 1px solid #ddd;
}
.contents tr td .image {
margin-top: 24px;
}
.image {
text-align: left;
margin-bottom: 8px;
}
a:link,
a:visited,
.contents a:link,
.contents a:visited,
a.el {
color: #0288d1;
font-weight: normal;
text-decoration: none;
}
div.contents {
margin-right: 12px;
}
.directory tr, .directory tr.even {
background: #7cb342;
border-top: 1px solid #7cb342;
}
.directory td,
.directory td.entry,
.directory td.desc {
background: rgba(255,255,255,.95);
border-left: none;
color: #212121;
padding-top: 10px;
padding-bottom: 10px;
padding-left: 8px;
padding-right: 8px;
}
.directory tr#row_0_ {
border-top-color: #7cb342;
}
.directory tr#row_0_ td {
background: #7cb342;
color: #fff;
font-size: 18px;
}
.memSeparator {
border-bottom: none;
}
.memitem {
background: #7cb342;
}
.memproto, dl.reflist dt {
background: #7cb342;
background-image: none;
border: none;
box-shadow: none;
-webkit-box-shadow: none;
color: #fff;
text-shadow: none;
}
.memproto .memtemplate,
.memproto a.el,
.memproto .paramname {
color: #fff;
}
.memdoc, dl.reflist dd {
border: none;
background-color: rgba(255,255,255,.95);
background-image: none;
box-shadow: none;
-webkit-box-shadow: none;
-webkit-border-bottom-left-radius: 0;
-webkit-border-bottom-right-radius: 0;
}
.memitem, table.doxtable, table.memberdecls {
margin-bottom: 24px;
}
table.doxtable th {
background: #7cb342;
}
table.doxtable tr {
background: #7cb342;
border-top: 1px solid #7cb342;
}
table.doxtable td, table.doxtable th {
border: none;
padding: 10px 8px;
}
table.doxtable td {
background-color: rgba(255,255,255,.95);
}
.memberdecls {
background: #7cb342;
border-top: 1px solid #7cb342;
}
.memberdecls .heading h2 {
border-bottom: none;
color: #fff;
font-size: 110%;
font-weight: bold;
margin: 0 0 0 6px;
}
.memberdecls tr:not(.heading) td {
background-color: rgba(255,255,255,.95);
}
h1, h2, h2.groupheader, h3, h4, h5, h6 {
color: #212121;
}
h1 {
border-bottom: 1px solid #ebebeb;
font: 400 28px/32px Roboto,sans-serif;
letter-spacing: -.01em;
margin: 40px 0 20px;
padding-bottom: 3px;
}
h2, h2.groupheader {
border-bottom: 1px solid #ebebeb;
font: 400 23px/32px Roboto,sans-serif;
letter-spacing: -.01em;
margin: 40px 0 20px;
padding-bottom: 3px;
}
h3 {
font: 500 20px/32px Roboto,sans-serif;
margin: 32px 0 16px;
}
h4 {
font: 500 18px/32px Roboto,sans-serif;
margin: 32px 0 16px;
}
ol,
ul {
margin: 0;
padding-left: 40px;
}
ol {
list-style: decimal outside;
}
ol ol {
list-style-type: lower-alpha;
}
ol ol ol {
list-style-type: lower-roman;
}
ul {
list-style: disc outside;
}
li,
li p {
margin: 8px 0;
padding: 0;
}
div.summary
{
float: none;
font-size: 8pt;
padding-left: 5px;
width: calc(100% - 10px);
text-align: left;
display: block;
}
div.ingroups {
margin-top: 8px;
}
div.fragment {
border: 1px solid #ddd;
color: #455a64;
font: 14px/20px Roboto Mono, monospace;
padding: 8px;
}
div.line {
line-height: 1.5;
font-size: inherit;
}
code, pre {
color: #455a64;
background: #f7f7f7;
font: 400 100% Roboto Mono,monospace;
padding: 1px 4px;
}
span.preprocessor, span.comment {
color: #0b8043;
}
span.keywordtype {
color: #0097a7;
}
.paramname {
color: #ef6c00;
}
.memTemplParams {
color: #ef6c00;
}
span.mlabel {
background: rgba(255,255,255,.25);
border: none;
}
blockquote {
border: 1px solid #ddd;
}

3001
docs/source/tutorial.md Normal file

File diff suppressed because it is too large Load Diff

19
extensions.bzl Normal file
View File

@@ -0,0 +1,19 @@
"""Bzlmod extensions"""
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file")
def _non_module_dependencies_impl(_ctx):
"""Non module dependencies"""
http_file(
name = "bazel_linux_x86_64",
downloaded_file_path = "bazel",
executable = True,
sha256 = "e78fc3394deae5408d6f49a15c7b1e615901969ecf6e50d55ef899996b0b8458",
urls = [
"https://github.com/bazelbuild/bazel/releases/download/6.3.2/bazel-6.3.2-linux-x86_64",
],
)
non_module_dependencies = module_extension(
implementation = _non_module_dependencies_impl,
)

View File

@@ -8,9 +8,9 @@
// Ensure the included flatbuffers.h is the same version as when this file was
// generated, otherwise it may not be compatible.
static_assert(FLATBUFFERS_VERSION_MAJOR == 23 &&
FLATBUFFERS_VERSION_MINOR == 5 &&
FLATBUFFERS_VERSION_REVISION == 26,
static_assert(FLATBUFFERS_VERSION_MAJOR == 25 &&
FLATBUFFERS_VERSION_MINOR == 2 &&
FLATBUFFERS_VERSION_REVISION == 10,
"Non-compatible flatbuffers version included");
namespace flatbuffers {

View File

@@ -13,7 +13,7 @@ public struct Galaxy : IFlatbufferObject
{
private Table __p;
public ByteBuffer ByteBuffer { get { return __p.bb; } }
public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_23_5_26(); }
public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_2_10(); }
public static Galaxy GetRootAsGalaxy(ByteBuffer _bb) { return GetRootAsGalaxy(_bb, new Galaxy()); }
public static Galaxy GetRootAsGalaxy(ByteBuffer _bb, Galaxy obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); }
public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); }

View File

@@ -13,7 +13,7 @@ public struct Universe : IFlatbufferObject
{
private Table __p;
public ByteBuffer ByteBuffer { get { return __p.bb; } }
public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_23_5_26(); }
public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_2_10(); }
public static Universe GetRootAsUniverse(ByteBuffer _bb) { return GetRootAsUniverse(_bb, new Universe()); }
public static Universe GetRootAsUniverse(ByteBuffer _bb, Universe obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); }
public static bool VerifyUniverse(ByteBuffer _bb) {Google.FlatBuffers.Verifier verifier = new Google.FlatBuffers.Verifier(_bb); return verifier.VerifyBuffer("", false, UniverseVerify.Verify); }

View File

@@ -1,5 +1,5 @@
// automatically generated by the FlatBuffers compiler, do not modify
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names
library flatbuffers.goldens;

Some files were not shown because too many files have changed in this diff Show More