Compare commits

..

118 Commits

Author SHA1 Message Date
Derek Bailey
0100f6a577 FlatBuffers Version 23.5.26 (#7976) 2023-05-26 10:33:09 -07:00
swimar
e0a87e36d5 Update java pom.xml file to allow flatbuffers-java maven package to be compiled under java 8, and pulled in as a dependency to a project using java 8. (#7893) (#7894)
Co-authored-by: Derek Bailey <derekbailey@google.com>
Co-authored-by: Paulo Pinheiro <paulovictor.pinheiro@gmail.com>
2023-05-22 09:18:37 +02:00
Derek Bailey
b67f1ad6d0 don't emit flatbuffers include in bfbs generated output (#7968) 2023-05-17 21:13:16 -07:00
Derek Bailey
ae6753684e switch back to having T explicitly defined in CreateVector (#7967) 2023-05-17 13:23:34 -07:00
Chih-Hsuan Yen
a352bdbc34 Fix python tests (#7960)
* Don't generate types unless --python-typing specified

Fixes https://github.com/google/flatbuffers/issues/7944

* Fix incorrect import statements

Fixes https://github.com/google/flatbuffers/issues/7951

* Fix $PYTHONPATH in PythonTest.sh

Regressed from https://github.com/google/flatbuffers/pull/7529

* PythonTest: fail if something goes wrong

GitHub Actions runs `bash PythonTest.sh`, and thus failures were not
visible.

* Build flatc for Python tests

* Regenerate codes

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-05-17 13:10:51 -07:00
sssooonnnggg
cb14043f82 fix(rust): fixed rust namer isses, resolve #7865 and ##7782 (#7964)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-05-17 19:54:49 +02:00
Derek Bailey
d64dc6200a Switch to using alias instead of a typedef for FlatBufferBuilder (#7966) 2023-05-17 10:40:02 -07:00
sssooonnnggg
ea7cfcd591 chore: add rust windows test to CI, fix RustTest.bat (#7963)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-05-16 16:06:41 -07:00
Daniel Frederick Crisman
067553156a README.md: SemVer case typo (#7962)
SemVer (if we are capitalizing it) has a capital V. See the third
sub-header at
https://semver.org/#semantic-versioning-specification-semver
"Semantic Versioning Specification (SemVer)"

Update the text in Versioning section
2023-05-16 09:46:47 -07:00
sssooonnnggg
b128b802d9 feat: Support union underlying type for TS/JS (#7961) 2023-05-15 13:18:49 -07:00
sssooonnnggg
1d3afb90c5 feat(C++): Support underlying_type for union (#7954)
* feat(C++): support underlying type for union

* chore: add conform checks for underlying type changes
2023-05-14 21:22:38 -07:00
Derek Bailey
fe5e4c71c5 remove flatbuffers tests from android (#7959) 2023-05-12 21:49:33 -07:00
Derek Bailey
17b9eed4e1 switch to interface library for flatsample 2023-05-12 21:23:51 -07:00
Derek Bailey
cbc8872b99 fix Mac build about gen sources and multiple targets 2023-05-12 17:11:18 -07:00
Derek Bailey
05743591e1 remove and auto-generate arrays_test_generated.h 2023-05-12 16:44:28 -07:00
Derek Bailey
2bc2529245 remove and auto-generate alignment_test_generated.h 2023-05-12 16:26:21 -07:00
sssooonnnggg
18cadc79c1 fix(TS): fixed incorrect function name when importing unionTo functions (#7958) 2023-05-12 10:49:50 -07:00
Wouter van Oortmerssen
426f3b8bf2 Missing GenTextFile decl 2023-05-11 18:26:06 -07:00
Wouter van Oortmerssen
950a71ab89 Rename GenerateText
to make it a compile-time breaking change, to alert any users to the new meaning of the return value
2023-05-11 18:14:27 -07:00
Derek Bailey
86486a1735 run scripts/clang-format-all.sh 2023-05-11 12:23:49 -07:00
Derek Bailey
c2f764c22b add GetSizePrefixedBufferLength() 2023-05-11 12:22:05 -07:00
Derek Bailey
e97ff95970 Change SizedPrefixed verifier to be <= provided size 2023-05-11 12:22:05 -07:00
Derek Bailey
33212657ae Change SizedPrefixed verifier to be <= provided size (#7957)
* Change SizedPrefixed verifier to be <= provided size

* add GetSizePrefixedBufferLength()
2023-05-11 12:21:50 -07:00
Derek Bailey
66e9d9823a fixed other occurenace of big buffer 2023-05-11 09:39:54 -07:00
Derek Bailey
9fc153a8f8 remove large buffer creation in test to speed it up 2023-05-11 09:34:50 -07:00
Philipp Schrader
c2bf810638 Fix //tests/ts:bazel_repository_test (#7952)
The test was not actually invoking the bazel that was downloaded with
the `http_file` rule. I failed to add `executable = True` to the
`http_file` call. This caused the test to ignore that bazel binary and
went to the next one on the system.

This patch fixes the issue by adding the missing attribute. Also, this
patch changes the check in the test to make sure that the downloaded
file is indeed executable.
2023-05-10 21:35:58 -07:00
Derek Bailey
0ce6957763 remove unneeed grpc include 2023-05-10 16:41:39 -07:00
Derek Bailey
82c6712606 make loop variable final in dart 2023-05-10 16:30:12 -07:00
Derek Bailey
b5957975c5 rename __suppress_ubsan to FLATBUFFERS_SUPPRESS_UBSAN 2023-05-10 14:16:31 -07:00
Derek Bailey
85f71321fd Update README.md
Added Quick State to the main readme file
2023-05-10 13:56:13 -07:00
Derek Bailey
3e6cd51b63 fixed bfbs gen to pass extra options (#7949) 2023-05-09 22:42:31 -07:00
Derek Bailey
10b79d87c1 removed extern code generation declarations preferring direct includes (#7948)
* removed extern code generation definitions, preferring direct includes

* add static to functions

* remove idl_gen_lua
2023-05-09 21:50:28 -07:00
Derek Bailey
16a7df46f0 fix --conform raising No generators registered error 2023-05-09 20:37:32 -07:00
Derek Bailey
76f5e9816a fix out-of-source builds with cmake (#7946) 2023-05-09 20:33:54 -07:00
Björn Harrtell
368428cb94 Upgrade package.json dependencies (#7933)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-05-09 20:33:17 -07:00
Derek Bailey
72b56fd081 FlatBuffers Version 23.5.9 (#7945) 2023-05-09 09:33:30 -07:00
Derek Bailey
63b7b25289 FlatBuffers 64 for C++ (#7935)
* First working hack of adding 64-bit. Don't judge :)

* Made vector_downward work on 64 bit types

* vector_downward uses size_t, added offset64 to reflection

* cleaned up adding offset64 in parser

* Add C++ testing skeleton for 64-bit

* working test for CreateVector64

* working >2 GiB buffers

* support for large strings

* simplified CreateString<> to just provide the offset type

* generalize CreateVector template

* update test_64.afb due to upstream format change

* Added Vector64 type, which is just an alias for vector ATM

* Switch to Offset64 for Vector64

* Update for reflection bfbs output change

* Starting to add support for vector64 type in C++

* made a generic CreateVector that can handle different offsets and vector types

* Support for 32-vector with 64-addressing

* Vector64 basic builder + tests working

* basic support for json vector64 support

* renamed fields in test_64bit.fbs to better reflect their use

* working C++ vector64 builder

* Apply --annotate-sparse-vector to 64-bit tests

* Enable Vector64 for --annotate-sparse-vectors

* Merged from upstream

* Add `near_string` field for testing 32-bit offsets alongside

* keep track of where the 32-bit and 64-bit regions are for flatbufferbuilder

* move template<> outside class body for GCC

* update run.sh to build and run tests

* basic assertion for adding 64-bit offset at the wrong time

* started to separate `FlatBufferBuilder` into two classes, 1 64-bit aware, the other not

* add test for nested flatbuffer vector64, fix bug in alignment of big vectors

* fixed CreateDirect method by iterating by Offset64 first

* internal refactoring of flatbufferbuilder

* block not supported languages in the parser from using 64-bit

* evolution tests for adding a vector64 field

* conformity tests for adding/removing offset64 attributes

* ensure test is for a big buffer

* add parser error tests for `offset64` and `vector64` attributes

* add missing static that GCC only complains about

* remove stdint-uintn.h header that gets automatically added

* move 64-bit CalculateOffset internal

* fixed return size of EndVector

* various fixes on windows

* add SizeT to vector_downward

* minimze range of size changes in vector and builder

* reworked how tracking if 64-offsets are added

* Add ReturnT to EndVector

* small cleanups

* remove need for second Array definition

* combine IndirectHelpers into one definition

* started support for vector of struct

* Support for 32/64-vectors of structs + Offset64

* small cleanups

* add verification for vector64

* add sized prefix for 64-bit buffers

* add fuzzer for 64-bit

* add example of adding many vectors using a wrapper table

* run the new -bfbs-gen-embed logic on the 64-bit tests

* remove run.sh and fix cmakelist issue

* fixed bazel rules

* fixed some PR comments

* add 64-bit tests to cmakelist
2023-05-09 09:16:30 -07:00
RishabhDeep Singh
13fc75cb6b FlatBuffers Version 23.5.8 (#7943) 2023-05-09 08:05:25 -07:00
RishabhDeep Singh
e6e38a8d17 Add #!/usr/bin/bash to release.sh (#7942) 2023-05-08 14:20:14 -07:00
Derek Bailey
d9f2cc2d62 add key_field to compiled tests 2023-05-08 13:54:24 -07:00
Derek Bailey
197ae6cc7e add rest of golden language directories 2023-05-05 14:22:55 -07:00
Derek Bailey
489d9735e9 add rest of golden language directories 2023-05-05 14:15:48 -07:00
Derek Bailey
3308444147 Add goldens directory 2023-05-05 13:43:07 -07:00
Derek Bailey
ef5ae488dd Rework cmake flatc codegeneration (#7938)
* start fixing the code generation steps

* reworked flatc generation in cmake
2023-05-05 12:08:09 -07:00
Derek Bailey
08efe60954 remove defining generated files in test srcs 2023-05-04 16:25:50 -07:00
Derek Bailey
01a7bc3c58 Add binary schema reflection (#7932)
* Add binary schema reflection

* remove not-used parameter

* move logic from object API to base API

* forward declare

* remove duplicate code gen that was stompping on the edits

* reduce to just typedef generation

* fixed bazel rules to not stomp

* more bazel fixes to support additional generated files
2023-05-04 16:12:45 -07:00
Wouter van Oortmerssen
67084b9921 Fix missing return error string for GenerateText 2023-05-03 13:23:53 -07:00
Wouter van Oortmerssen
ed11b08fc9 GenerateText gives text error on failure 2023-05-03 13:03:00 -07:00
Philipp Schrader
c1e7aee489 Migrate from rules_nodejs to rules_js/rules_ts (take 2) (#7928)
* Migrate from rules_nodejs to rules_js/rules_ts (take 2)

This is the second version of patch #7923. The first version got
reverted because bazel query was failing:

    $ bazel --nosystem_rc --nohome_rc query tests(set('//...')) except tests(attr("tags", "manual", set('//...')))
    ERROR: Traceback (most recent call last):
    	File "/workdir/tests/ts/bazel_repository_test_dir/BUILD", line 6, column 22, in <toplevel>
    		npm_link_all_packages(name = "node_modules")
    	File "/var/lib/buildkite-agent/.cache/bazel/_bazel_buildkite-agent/ec321eb2cc2d0f8f91b676b6d4c66c29/external/npm/defs.bzl", line 188, column 13, in npm_link_all_packages
    		fail(msg)
    Error in fail: The npm_link_all_packages() macro loaded from @npm//:defs.bzl and called in bazel package 'tests/ts/bazel_repository_test_dir' may only be called in bazel packages that correspond to the pnpm root package '' and pnpm workspace projects ''

This was happening because the `.bazelrc` file only added
`--deleted_packages` to the `build` command. We also need it for the
`query` command. This second version of the patch fixes that.

Original commit message:

This patch migrates the current use of rules_nodejs to the new rules_js.
rules_js is the intended replacement of rules_nodejs as per this note:
https://github.com/aspect-build/rules_js#relationship-to-rules_nodejs

> rules_js is an alternative to the build_bazel_rules_nodejs Bazel module
> and accompanying npm packages hosted in
> https://github.com/bazelbuild/rules_nodejs, which is now
> unmaintained. All users are recommended to use rules_js instead.

There are a few notable changes in this patch:
1. The `flatbuffer_ts_library` macro no longer accepts a `package_name`
   attribute. This is because rules_js appears to manage the import
   naming of dependencies via top-level `npm_link_package` targets.
   Users will have to migrate.
2. I added a few more arguments to `flatbuffer_library_public()`. These
   helped with exposing esbuild to `ts/compile_flat_file.sh`.
3. I pinned the version of `typescript` in `package.json` so that
   rules_ts can download the exact same version. rules_ts doesn't know
   what to do if the version isn't exact.
4. Since rules_js uses the pnpm locking mechanism, we now have a
   `pnpm-lock.yaml` file instead of a yarn lock file.
4. I added bazel targets for a few of the existing tests in `tests/ts`.
   They can be run with `bazel test //test/ts:all`. Since there is no
   flexbuffers bazel target, I did not add a bazel target for the
   corresponding test.
5. I added a separate workspace in `tests/ts/bazel_repository_test_dir/`
   to validate that the flatbuffers code can be imported as an external
   repository. You can run the test with
   `bazel test //test/ts:bazel_repository_test`. For this to work, I
   needed to expose a non-trivial chunk of the flatbuffers code to the
   test. I achieved this through some recursive `distribution`
   filegroups. This is inspired by rules_python's workspace tests.

I did not do anything special to validate that the `gen_reflections`
parameter works the same. This patch doesn't change anything about
the TypeScript generation.

As a side note: I am not an expert with rules_js. This patch is my
attempt based on my limited understanding of the rule set.

Fixes #7817

* Fix the query

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-05-03 11:48:15 -07:00
Derek Bailey
75143f836b fix possible null dereference for nested_root accessor 2023-05-03 00:14:27 -07:00
Derek Bailey
fb4f6fb894 fix possible null dereference for nested_root accessor 2023-05-02 23:50:20 -07:00
Derek Bailey
19d8942943 flat_buffers.dart: mark const variable finals for internal Dart linters 2023-05-01 09:55:47 -07:00
Derek Bailey
dbce69c63b more window fixes 2023-04-29 00:43:34 -07:00
Derek Bailey
aeba096403 fixed some windows warnings (#7929) 2023-04-28 23:22:41 -07:00
Derek Bailey
966aae2144 inject no long for FBS generation to remove logs in flattests (#7926)
* inject no long for FBS generation to remove logs in flattests

* updated blaze rules
2023-04-28 13:40:38 -07:00
Derek Bailey
e7dc252b0e Revert "Migrate from rules_nodejs to rules_js/rules_ts (#7923)" (#7927)
This reverts commit 4172c3f0bd.
2023-04-28 12:58:49 -07:00
Philipp Schrader
4172c3f0bd Migrate from rules_nodejs to rules_js/rules_ts (#7923)
* Start using pnpm

* Add @npm

* get more stuff set up

* Get the analysis phase passing.

* Get esbuild working?

* Get it compiling?

    $ bazel build //tests/ts/...

* Try to get the test working

* test is passing

* Get the other tests working

* clarify comment

* clean up a bit

* Try to add another test

* Add another test

* clean up more

* remove unused reference

* Add e2e test

* Get more of the test working

* add lock file

* Get test working on its own

* Get e2e test passing

* fix infinite recursion

* Add comments

* clean up some more

* clean up more again

* Source typescript version from package.json

* run buildifier

* lint

* Fix unset `extra_env`

* Incorporate feedback

* run buildifier

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-04-28 18:17:45 +00:00
Aaron Riekenberg
417821fdd7 Only generate @kotlin.ExperimentalUnsigned annotation on create*Vector methods having an unsigned array type parameter. (#7881)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-04-28 17:10:01 +00:00
Berke
c192ab423b additional check for absl::string_view availability (#7897)
absl::string_view is uses std::string_view when available. It already checks if std::string_view is available in the earlier code.
It should only use absl::string_view implementation.

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-04-28 16:51:11 +00:00
Max Burke
a397dd7e8c Optionally generate Python type annotations (#7858)
* optionally generate type prefixes and suffixes for python code

* fix codegen error when qualified name is empty

* WIP: Python typing

* more progress towards python typing

* Further iterate on Python generated code typing

* clang-format

* Regenerate code

* add documentation for Python type annotations option

* generate code with Python type annotations

* handle forward references

* clang-format
2023-04-28 09:38:29 -07:00
Jongwoo Han
6eae49a79a Replace deprecated command with environment file (#7921)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-04-25 22:50:37 -07:00
Nikita Sokolov
f6af2087ee drop glibc from runtime dependencies (#7906)
https://github.com/google/flatbuffers/issues/7696
The binary size grows from 5.8MB to 7.2MB, but this way it works on Ubuntu 18.04 and amazonlinux.
2023-04-25 22:39:37 -07:00
Adam Oleksy
ab716ee41d Make JSON supporting advanced union features (#7869)
This change allows user to decode binary with given schema to JSON
representation when schema defines union with struct.

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-04-26 05:37:06 +00:00
KerstinKeller
d6d83c3a92 Allow to use functions from BuildFlatBuffers.cmake from a flatbuffers installation installed with CMake. (#7912)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-04-26 05:27:14 +00:00
José Luis Millán
aa6848fbf6 TS/JS: Use TypeError instead of Error when appropriate (#7910)
Ie: when the needed conditions are not satisfied in order to perform a
 given action.
2023-04-25 22:22:06 -07:00
Jeroen Demeyer
6c8a8d054d Go: make generated code more compliant to "go fmt" (#7907)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-04-26 05:19:07 +00:00
Jeroen Demeyer
63495b935a Support file_identifier in Go (#7904)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-04-26 05:15:09 +00:00
Max Burke
56ecc1f548 Optionally generate type prefixes and suffixes for python code (#7857)
* optionally generate type prefixes and suffixes for python code

* fix codegen error when qualified name is empty

* generated code updated
2023-04-25 21:38:16 -07:00
Jeroen Demeyer
3fda20d7c7 Go: add test for FinishWithFileIdentifier (#7905)
Co-authored-by: Michael Le <michael.le647@gmail.com>
2023-04-11 17:08:04 -07:00
Jeroen Demeyer
fa3fa91936 Fix go_sample.sh (#7903) 2023-04-11 12:40:00 -07:00
Björn Harrtell
52f2596e15 [TS/JS] Upgrade dependencies (#7889)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-04-06 02:00:23 +00:00
Khanh Nguyen
0916f1c87e Add a FileWriter interface (#7821)
* Add a FileWriter interface

* Change interface

* Provide 2 impl for File interface: FileManager & FileNameManager

* Update

* update

* Update

* Add file_writer file

* Update

* Format files

* Update based on review

* Update

* Format bzl file

* Add LoadFile function

* Format

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-04-06 01:49:29 +00:00
Björn Harrtell
0888e7cb4d TS/JS: Use minvalue from enum if not found (#7888)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-04-06 01:26:05 +00:00
tira-misu
876a64aae1 [CS] Verifier (#7850)
* Fix C/C++ Create<Type>Direct with sorted vectors

If a struct has a key the vector has to be sorted. To sort the vector
you can't use "const".

* Changes due to code review

* Improve code readability

* Add generate of JSON schema to string to lib

* option indent_step is supported

* Remove unused variables

* Fix break in test

* Fix style to be consistent with rest of the code

* [TS] Fix reserved words as arguments (#6955)

* [TS] Fix generation of reserved words in object api (#7106)

* [TS] Fix generation of object api

* [TS] Fix MakeCamel -> ConvertCase

* [C#] Fix collision of field name and type name

* [TS] Add test for struct of struct of struct

* Update generated files

* Add missing files

* [TS] Fix query of null/undefined fields in object api

* Add .Net verfier

* Add some fuzz tests for .Net

* Remove additional files

* Fix .net test

* Changes due to PR

* Fix generated files

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-04-06 00:29:14 +02:00
Daniel Frederick Crisman
2803983c70 README.md: PyPI case typo (#7880)
PyPI has three capital letters. See the front page of the service:
https://pypi.org/
"The Python Package Index (PyPI) ..."

Update the Python link under "Supported programming languages"

Co-authored-by: Michael Le <michael.le647@gmail.com>
2023-03-30 13:32:16 -07:00
Michael Le
88dd92de40 Update go documentation link to point to root module (#7879)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-03-29 10:50:54 -07:00
blindspotbounty
477b1b5d13 use Bool for flatbuffers bool instead of Byte (#7876)
Add test for Bool type in swift

Co-authored-by: mustiikhalil <26250654+mustiikhalil@users.noreply.github.com>
2023-03-27 01:45:48 +02:00
phenixxy
1cb1c4baee fix using null string in vector (#7872)
Use 0 offset as special value. 0 offset is not a valid relative offset, so it's safe to use 0 offset to indicate value is null.

https://github.com/google/flatbuffers/issues/7846
2023-03-24 03:15:34 +00:00
Derek Bailey
50cdf92e1e Add flatbuffers-64 branch to CI for pushes 2023-03-15 23:58:26 -07:00
Jeffrey Smith
9a7fb4d68a made changes to the rust docs so they would compile. new_with_capacity is deprecated should use with_capacity, get_root_as_monster should be root_as_monster (#7871) 2023-03-16 00:29:57 +00:00
SmashedFrenzy16
3cb27fa241 Adding comment for code clarification (#7856)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-03-14 20:14:05 -05:00
Paulo Pinheiro
d3d7e2ef99 ToCamelCase() when kLowerCamel now converts first char to lower. (#7838)
ToCamelCase(input, true) converts first char to upper case, but
ToCamelCase(input, false) keeps the case of the first char. We are
changing its behavior to force a lower case.

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-03-15 01:09:24 +00:00
Ben Beasley
d4d355d883 Fix help output for --java-checkerframework (#7854) 2023-03-09 06:53:37 +00:00
SmashedFrenzy16
0fde16e426 Update filename to README.md and improve formatting (#7855) 2023-03-09 04:55:13 +00:00
Derek Bailey
32a6744286 Increase limit on stale.yml items processed 2023-03-03 17:02:14 -08:00
Derek Bailey
42ee479c31 Allow manual runs of stale.yml 2023-03-03 16:59:45 -08:00
Derek Bailey
df007dfde8 Update stale.yml
Shorten the PR staleness from 6 months to 3 weeks + 1 week notice. PRs become much harder to deal with the old they become due to merge conflicts and divergence.

Updated to stale@v7.0.0
2023-03-03 16:52:14 -08:00
Derek Bailey
d44ce00af1 Updated remaining usages of LICENSE.txt 2023-03-03 12:01:08 -08:00
Derek Bailey
01834de25e FlatBuffers Version 23.3.3 (#7852) 2023-03-03 11:46:55 -08:00
Chuck Atkins
6f9ea7c23c Add Java reflection bindings to the distribution (#7851)
The distributions for C++ and Python include the generated reflection
bindings but are currently missing from the other language packages.
This will bring the Java package generated for releases closer to
feature parity with the C++ and Python release artifacts.
2023-03-03 11:14:07 -08:00
CodeMaster7000
de9791e0a9 Update pom.xml (#7849)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-03-02 23:47:54 -08:00
José Luis Millán
3e778aca4d TS/JS: Export object based classes on entry (#7822)
* TS/JS: Export object based classes on entry

Along with the non object ones, for consistency. This is a regression
introduced recently.

Before:
 `export { UpdateSettingsRequest } from './worker/update-settings-request.js';`

Now:
 `export { UpdateSettingsRequest, UpdateSettingsRequestT } from './worker/update-settings-request.js';`

* only export object based classes for structs

Enums are not elegible.

---------

Co-authored-by: Björn Harrtell <bjornharrtell@users.noreply.github.com>
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-03-02 23:35:59 -08:00
Paulo Pinheiro
01f4138618 [Android][Kotlin] fixed build after decomission of jcenter and gradle update (#7840)
* [Android] fixed build after decomission of jcenter

JCenter[1] has been removed and now is failing android build. This
change updates the configuration to remove this and few other warnings.

1 - https://developer.android.com/studio/build/jcenter-migration

* [Kotlin] fix build for latest gradle version 8.0.1

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-03-02 23:27:06 -08:00
Chuck Atkins
b90cc35a10 Add a --java-package-prefix option to flatc (#7848)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-03-02 21:52:03 -08:00
Cedric Schmeits
79d6abb42e Added GENERATE_<TARGET> to flatbuffers_generate_headers (#7845)
The generation of the library interface supplied by this function only
works within the same directory as that the target was defined. By
adding a custom target named GENERATE_<TARGET> now also interface files
will be generated by making a target dependend on the generate target.

Example:
/CMakeLists.txt
  set(MY_INCL_SRC ${CMAKE_CURRENT_SOURCE_DIR}/fbs/my_incl.fbs)
  flatbuffers_generate_headers(TARGET my_incl
                               SCHEMAS ${MY_INCL_SRC})

  add_subdirectory(app)

/app/CMakeLists.txt
  add_executable(app src/test.cpp)
  target_link_libraries(app my_incl)
  add_dependencies(app GENERATE_my_incl)

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-03-02 21:47:18 -08:00
tira-misu
d1e4daa178 [CS] Naming collision if field has same name as table and used as key (#7842)
* Fix C/C++ Create<Type>Direct with sorted vectors

If a struct has a key the vector has to be sorted. To sort the vector
you can't use "const".

* Changes due to code review

* Improve code readability

* Add generate of JSON schema to string to lib

* option indent_step is supported

* Remove unused variables

* Fix break in test

* Fix style to be consistent with rest of the code

* [TS] Fix reserved words as arguments (#6955)

* [TS] Fix generation of reserved words in object api (#7106)

* [TS] Fix generation of object api

* [TS] Fix MakeCamel -> ConvertCase

* [C#] Fix collision of field name and type name

* [TS] Add test for struct of struct of struct

* Update generated files

* Add missing files

* [TS] Fix query of null/undefined fields in object api

* Fix collision if field name is equal to table name and used as key in an array

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-03-02 21:42:27 -08:00
Khanh Nguyen
4a34cd70dc Add Code Generator for idl_gen_fbs to parse .proto files (#7832)
* Add code generator for proto files

* Update

* Add --proto to script

* Remove cmt

* Move proto parsing logic into else block to share same set up logic for code_generator

* Remove IsValidCodeGenerator
2023-03-02 10:01:44 -08:00
Henner Zeller
6a9cd4411f Editorconfig: als configure to trim whitespaces end EOL. (#7833)
Signed-off-by: Henner Zeller <hzeller@google.com>
2023-02-27 19:56:18 -08:00
Saman
f7a75173f1 Move defined part to idl.h (#7823) 2023-02-17 20:34:32 -08:00
Even Rouault
a56f9ec50e Only use absl headers if C++14 is available. (#7824)
If flatbuffers is built in C++11 mode, but there is a recent version of
absl which requires C++14, the build will fail.
Cf https://github.com/MapServer/MapServer/issues/6822 for the use case
that triggered this.
2023-02-15 10:56:16 -08:00
Derek Bailey
4c71f87619 fixed bad math for --annotate-sparse-vectors 2023-02-06 22:08:09 -08:00
chrismue
6af83a7d05 Sample adjusted for Python3 (#7819)
Co-authored-by: chrismue <chrismue.gitlab@gmail.com>
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-02-06 21:47:39 -08:00
Derek Bailey
535ead8d8c [Annotated Buffers] Improve efficiency (#7820)
* AnnotatedBinaryTextGen switch to ofstream instead of building giant string

* Add --annotate-sparse-vectors to reduce AFB size
2023-02-06 21:42:44 -08:00
Björn Harrtell
85aee1f5c3 Simplify and fix TypeScript compilation output (#7815)
* Simplify and fix TypeScript compilation output

* Revert deps upgrade
2023-02-06 13:10:20 -08:00
Derek Bailey
f3a3f45159 use switch statements for BASE_TYPE_ lookups (#7813) 2023-02-05 12:29:09 -08:00
Derek Bailey
02d7859f8b explicitly declare enum values (#7811) 2023-02-03 15:33:04 -08:00
Derek Bailey
5785784c8a proto_test.cpp don't warn about gaps 2023-02-02 15:57:55 -08:00
Derek Bailey
0fb5519585 Fixed vtable duplication for binary annotator (#7809) 2023-02-02 10:39:39 -08:00
Saman
f838017860 Parsing from proto should keep field ID. (fixes #7645) (#7655)
* Parsing from proto should keep field ID. (fixes #7645)

* Fix failed tests

* Fix windows warning

* Improve attribute generation in proto to fbs

* Check if id is used twice. fix Some clang-format problems

* Test if fake id can solve the test problem

* Validate proto file in proto -> fbs generation.

* Fix error messages

* Ignore id in union

* Add keep proto id for legacy and check gap flag have been added. Reserved id will be checked.

* Add needed flags

* unit tests

* fix fromat problem. fix comments and error messages.

* clear

* More unit tests

* Fix windows build

* Fix include problems

* Fake commit to invoke rebuild

* Fix buzel build

* Fix some issues

* Fix comments, fix return value and sort for android NDK

* Fix return type

* Break down big function

* Place todo

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-02-01 11:17:35 -08:00
Khanh Nguyen
08ebd202e2 Final refactor for bfsb_generator* and text generator (#7806)
* Refactor BfbsGenerator to use CodeGenerator interface

* Update

* Refactor bfbs generator

* Refactor bfbs generator for lua and nim. Remove old code that use Generator
interface.

* Update import

* Update CMakeLists

* Update BUILD file

* Update BUILD file for src

* Remove from Android CMakeLists and add error message

* Update

* Add generate root file function to Code Generator interface

* Update

* Update

* Minor format fix
2023-01-31 09:35:34 -08:00
Bernie Innocenti
a6f4194489 Fix std::span autodetection (#7805)
The current detection method fails on GCC 12.2 with -std=c++20 because
the __cpp_lib_span macro is undefined.

As per https://en.cppreference.com/w/cpp/utility/feature_test ,
__cpp_lib_span requires including either <version> or <span>.

Since both these headers were added in C++20, checking for C++20 is
sufficient (and simpler than using the library feature-test macro).

Signed-off-by: Bernie Innocenti <bernie@codewiz.org>
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-01-30 21:59:17 -08:00
CodeMaster7000
7fb785fd89 Rename LICENSE.txt to LICENSE (#7808)
* Update PackageDebian.cmake

* Rename LICENSE.txt to LICENSE

* Update readme.md

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-01-30 21:36:30 -08:00
Ilya Lavrenov
ca71fdfb9a Supported cmake 3.8 (#7801) 2023-01-29 23:00:57 -08:00
Khanh Nguyen
a105c26eca Refactor usage message (#7803)
* Update usage string formation

* Rework help message to use code generator interface

* update

* refactor
2023-01-28 13:17:36 -06:00
Khanh Nguyen
5b7a02d037 Code generator refactor bug fix (#7802)
* Swift should use swift generator

* Swift should use swift generator

Co-authored-by: Mo (Khanh) Nguyen <khhn@google.com>
2023-01-26 10:57:47 -08:00
Wen Sun
f5121615d9 Clean up extra white spaces (#7800)
* Clean up extra white spaces

* update

Co-authored-by: Wen Sun <sunwen@google.com>
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-01-25 17:37:03 +00:00
Khanh Nguyen
34c821f4ad Refactor languages to use CodeGenerator interface. (#7797)
* Refactor to use CodeGenerator interface.

- Move code to its own header file to be included in flatc_main.cpp
- Refactor code to use CodeGenerator interface for all languages

* Format all files

* remove lua code generator since it doesn't support bfbs generator

* Update CMakeLists file with new idl_gen_*.cpp and idl_gen_*.h files

* Add idl_gen_swift header file

* Add idl_gen_swift header file and update bazel file

* Remove CodeGenerator interface for idl_gen_text.*. Remove comments and extern declaration

* Reorder header and implementation files in CMakeLists.txt

* Add idl_gen_* header files to implementation files

* Update CMakeLists and remove unused import

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-01-25 09:05:48 -08:00
Wen Sun
802a3a056a [C++] Enable using struct and array of struct as key (#7741)
* add unit tests for support struct as key

* make changes to parser and add helper function to generate comparator for struct

* implement

* add more unit tests

* format

* just a test

* test done

* rerun generator

* restore build file

* address comment

* format

* rebase

* rebase

* add more unit tests

* rerun generator

* address some comments

* address comment

* update

* format

* address comment

Co-authored-by: Wen Sun <sunwen@google.com>
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-01-24 16:37:13 -08:00
587 changed files with 28742 additions and 14567 deletions

1
.bazelignore Normal file
View File

@@ -0,0 +1 @@
node_modules

4
.bazelrc Normal file
View File

@@ -0,0 +1,4 @@
# 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

View File

@@ -5,3 +5,4 @@ root = true
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true

1
.github/labeler.yml vendored
View File

@@ -52,7 +52,6 @@ kotlin:
lua:
- '**/*.lua'
- lua/**/*
- src/idl_gen_lua.cpp
- src/bfbs_gen_lua.cpp
lobster:

View File

@@ -9,6 +9,7 @@ on:
- "*" # new tag version, like `0.8.4` or else
branches:
- master
- flatbuffers-64
pull_request:
branches:
- master
@@ -29,7 +30,7 @@ jobs:
steps:
- uses: actions/checkout@v3
- name: cmake
run: CXX=${{ matrix.cxx }} cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON .
run: CXX=${{ matrix.cxx }} cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON -DFLATBUFFERS_STATIC_FLATC=ON .
- name: build
run: make -j
- name: test
@@ -59,11 +60,11 @@ jobs:
- name: Generate SLSA subjects - clang
if: matrix.cxx == 'clang++-12' && startsWith(github.ref, 'refs/tags/')
id: hash-clang
run: echo "::set-output name=hashes::$(sha256sum Linux.flatc.binary.${{ matrix.cxx }}.zip | base64 -w0)"
run: echo "hashes=$(sha256sum Linux.flatc.binary.${{ matrix.cxx }}.zip | base64 -w0)" >> $GITHUB_OUTPUT
- name: Generate SLSA subjects - gcc
if: matrix.cxx == 'g++-10' && startsWith(github.ref, 'refs/tags/')
id: hash-gcc
run: echo "::set-output name=hashes::$(sha256sum Linux.flatc.binary.${{ matrix.cxx }}.zip | base64 -w0)"
run: echo "hashes=$(sha256sum Linux.flatc.binary.${{ matrix.cxx }}.zip | base64 -w0)" >> $GITHUB_OUTPUT
build-linux-no-file-tests:
name: Build Linux with -DFLATBUFFERS_NO_FILE_TESTS
@@ -75,6 +76,28 @@ jobs:
- name: build
run: make -j
build-linux-out-of-source:
name: Build Linux with out-of-source build location
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: make build directory
run: mkdir build
- name: cmake
working-directory: build
run: >
CXX=clang++-12 cmake .. -G "Unix Makefiles" -DFLATBUFFERS_STRICT_MODE=ON
-DFLATBUFFERS_BUILD_CPP17=ON -DFLATBUFFERS_CPP_STD=17
- name: build
working-directory: build
run: make -j
- name: test
working-directory: build
run: pwd && ./flattests
- name: test C++17
working-directory: build
run: ./flattests_cpp17
build-linux-cpp-std:
name: Build Linux C++
runs-on: ubuntu-latest
@@ -165,7 +188,7 @@ jobs:
if: startsWith(github.ref, 'refs/tags/')
id: hash
shell: bash
run: echo "::set-output name=hashes::$(sha256sum Windows.flatc.binary.zip | base64 -w0)"
run: echo "hashes=$(sha256sum Windows.flatc.binary.zip | base64 -w0)" >> $GITHUB_OUTPUT
build-windows-2017:
name: Build Windows 2017
@@ -266,7 +289,7 @@ jobs:
- name: Generate SLSA subjects
if: startsWith(github.ref, 'refs/tags/')
id: hash
run: echo "::set-output name=hashes::$(shasum -a 256 MacIntel.flatc.binary.zip | base64)"
run: echo "hashes=$(shasum -a 256 MacIntel.flatc.binary.zip | base64)" >> $GITHUB_OUTPUT
build-mac-universal:
permissions:
@@ -309,7 +332,7 @@ jobs:
- name: Generate SLSA subjects
if: startsWith(github.ref, 'refs/tags/')
id: hash
run: echo "::set-output name=hashes::$(shasum -a 256 Mac.flatc.binary.zip | base64)"
run: echo "hashes=$(shasum -a 256 Mac.flatc.binary.zip | base64)" >> $GITHUB_OUTPUT
build-android:
name: Build Android (on Linux)
@@ -421,20 +444,32 @@ jobs:
# gradlew
run: gradle jvmMainClasses jvmTest jsTest jsBrowserTest
build-rust:
name: Build Rust
build-rust-linux:
name: Build Rust Linux
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: test
working-directory: tests
run: bash RustTest.sh
build-rust-windows:
name: Build Rust Windows
runs-on: windows-2019
steps:
- uses: actions/checkout@v3
- name: test
working-directory: tests
run: ./RustTest.bat
build-python:
name: Build Python
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: flatc
# FIXME: make test script not rely on flatc
run: cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_INSTALL=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF -DFLATBUFFERS_STRICT_MODE=ON . && make -j
- name: test
working-directory: tests
run: bash PythonTest.sh
@@ -560,7 +595,7 @@ jobs:
echo "$MAC_DIGESTS" | base64 -d >> checksums.txt
echo "$MACINTEL_DIGESTS" | base64 -d >> checksums.txt
echo "$WINDOWS_DIGESTS" | base64 -d >> checksums.txt
echo "::set-output name=digests::$(cat checksums.txt | base64 -w0)"
echo "digests=$(cat checksums.txt | base64 -w0)" >> $GITHUB_OUTPUT
provenance:
if: startsWith(github.ref, 'refs/tags/')

View File

@@ -1,9 +1,13 @@
name: Mark stale issues and pull requests
permissions: read-all
permissions:
issues: write
pull-requests: write
on:
# For manual tests.
workflow_dispatch:
schedule:
- cron: "30 20 * * *"
- cron: "30 20 * * *"
jobs:
stale:
@@ -11,14 +15,23 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v4.0.0
- uses: actions/stale@v7.0.0
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
stale-pr-message: 'This pull request is stale because it has been open 6 months with no activity. Please comment or this will be closed in 14 days.'
stale-issue-message: 'This issue is stale because it has been open 6 months with no activity. Please comment or this will be closed in 14 days.'
days-before-stale: 182 # 6 months
days-before-close: 14
operations-per-run: 1500
exempt-issue-labels: not-stale
exempt-pr-labels: not-stale
operations-per-run: 500
exempt-all-milestones: true
remove-stale-when-updated: true
stale-issue-message: 'This issue is stale because it has been open 6 months with no activity. Please comment or label `not-stale`, or this will be closed in 14 days.'
close-issue-message: 'This issue was automatically closed due to no activity for 6 months plus the 14 day notice period.'
days-before-issue-stale: 182 # 6 months
days-before-issue-close: 14 # 2 weeks
exempt-issue-labels: not-stale
stale-pr-message: 'This pull request is stale because it has been open 3 weeks with no activity. Please comment or label `not-stale`, or this will be closed in 7 days.'
close-pr-message: 'This pull request was automatically closed due to no activity for 3 weeks plus the 7 day notice period.'
days-before-pr-stale: 21 # 3 weeks
days-before-pr-close: 7 # 1 week
exempt-pr-labels: not-stale
exempt-draft-pr: false

1
.npmrc Normal file
View File

@@ -0,0 +1 @@
hoist=false

View File

@@ -1,3 +1,5 @@
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"])
@@ -6,6 +8,13 @@ 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",
@@ -25,6 +34,23 @@ config_setting(
],
)
filegroup(
name = "distribution",
srcs = [
"BUILD.bazel",
"WORKSPACE",
"build_defs.bzl",
"typescript.bzl",
"//grpc/src/compiler:distribution",
"//reflection:distribution",
"//src:distribution",
"//ts:distribution",
] + glob([
"include/flatbuffers/*.h",
]),
visibility = ["//visibility:public"],
)
# Public flatc library to compile flatbuffer files at runtime.
cc_library(
name = "flatbuffers",
@@ -41,13 +67,13 @@ filegroup(
"include/flatbuffers/allocator.h",
"include/flatbuffers/array.h",
"include/flatbuffers/base.h",
"include/flatbuffers/bfbs_generator.h",
"include/flatbuffers/buffer.h",
"include/flatbuffers/buffer_ref.h",
"include/flatbuffers/code_generator.h",
"include/flatbuffers/code_generators.h",
"include/flatbuffers/default_allocator.h",
"include/flatbuffers/detached_buffer.h",
"include/flatbuffers/file_manager.h",
"include/flatbuffers/flatbuffer_builder.h",
"include/flatbuffers/flatbuffers.h",
"include/flatbuffers/flex_flat_util.h",

View File

@@ -4,6 +4,64 @@ 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.
## [23.5.26 (May 26 2023)](https://github.com/google/flatbuffers/releases/tag/v23.5.26)
* Mostly bug fixing for 64-bit support
* Adds support for specifying underling type of unions in C++ and TS/JS (#7954)
## [23.5.9 (May 9 2023)](https://github.com/google/flatbuffers/releases/tag/v23.5.9)
* 64-bit support for C++ (#7935)
## [23.5.8 (May 8 2023)](https://github.com/google/flatbuffers/releases/tag/v23.5.8)
* add key_field to compiled tests
* Add golden language directory
* Rework cmake flatc codegeneration (#7938)
* remove defining generated files in test srcs
* Add binary schema reflection (#7932)
* Migrate from rules_nodejs to rules_js/rules_ts (take 2) (#7928)
* `flat_buffers.dart`: mark const variable finals for internal Dart linters
* fixed some windows warnings (#7929)
* inject no long for FBS generation to remove logs in flattests (#7926)
* Revert "Migrate from rules_nodejs to rules_js/rules_ts (#7923)" (#7927)
* Migrate from rules_nodejs to rules_js/rules_ts (#7923)
* Only generate @kotlin.ExperimentalUnsigned annotation on create*Vector methods having an unsigned array type parameter. (#7881)
* additional check for absl::string_view availability (#7897)
* Optionally generate Python type annotations (#7858)
* Replace deprecated command with environment file (#7921)
* drop glibc from runtime dependencies (#7906)
* Make JSON supporting advanced union features (#7869)
* Allow to use functions from `BuildFlatBuffers.cmake` from a flatbuffers installation installed with CMake. (#7912)
* TS/JS: Use TypeError instead of Error when appropriate (#7910)
* Go: make generated code more compliant to "go fmt" (#7907)
* Support file_identifier in Go (#7904)
* Optionally generate type prefixes and suffixes for python code (#7857)
* Go: add test for FinishWithFileIdentifier (#7905)
* Fix go_sample.sh (#7903)
* [TS/JS] Upgrade dependencies (#7889)
* Add a FileWriter interface (#7821)
* TS/JS: Use minvalue from enum if not found (#7888)
* [CS] Verifier (#7850)
* README.md: PyPI case typo (#7880)
* Update go documentation link to point to root module (#7879)
* use Bool for flatbuffers bool instead of Byte (#7876)
* fix using null string in vector (#7872)
* Add `flatbuffers-64` branch to CI for pushes
* made changes to the rust docs so they would compile. new_with_capacity is deprecated should use with_capacity, get_root_as_monster should be root_as_monster (#7871)
* Adding comment for code clarification (#7856)
* ToCamelCase() when kLowerCamel now converts first char to lower. (#7838)
* Fix help output for --java-checkerframework (#7854)
* Update filename to README.md and improve formatting (#7855)
* Update stale.yml
* Updated remaining usages of LICENSE.txt
## [23.3.3 (Mar 3 2023)](https://github.com/google/flatbuffers/releases/tag/v23.3.3)
* Refactoring of `flatc` generators to use an interface (#7797).
* Removed legacy cmake support and set min to 3.8 (#7801).
## [23.1.21 (Jan 21 2023)](https://github.com/google/flatbuffers/releases/tag/v23.1.20)
* Reworked entry points for Typescript/Javascript and compatibility for single

View File

@@ -59,6 +59,9 @@ function(build_flatbuffers flatbuffers_schemas
if(FLATBUFFERS_FLATC_EXECUTABLE)
set(FLATC_TARGET "")
set(FLATC ${FLATBUFFERS_FLATC_EXECUTABLE})
elseif(TARGET flatbuffers::flatc)
set(FLATC_TARGET flatbuffers::flatc)
set(FLATC flatbuffers::flatc)
else()
set(FLATC_TARGET flatc)
set(FLATC flatc)
@@ -157,6 +160,10 @@ endfunction()
# other flagc flags using the FLAGS option to change the behavior of the flatc
# tool.
#
# When the target_link_libraries is done within a different directory than
# flatbuffers_generate_headers is called, then the target should also be dependent
# the custom generation target called GENERATE_<TARGET>.
#
# Arguments:
# TARGET: The name of the target to generate.
# SCHEMAS: The list of schema files to generate code for.
@@ -182,6 +189,9 @@ endfunction()
# target_link_libraries(MyExecutableTarget
# PRIVATE my_generated_headers_target
# )
#
# Optional (only needed within different directory):
# add_dependencies(app GENERATE_my_generated_headers_target)
function(flatbuffers_generate_headers)
# Parse function arguments.
set(options)
@@ -204,6 +214,9 @@ function(flatbuffers_generate_headers)
if(FLATBUFFERS_FLATC_EXECUTABLE)
set(FLATC_TARGET "")
set(FLATC ${FLATBUFFERS_FLATC_EXECUTABLE})
elseif(TARGET flatbuffers::flatc)
set(FLATC_TARGET flatbuffers::flatc)
set(FLATC flatbuffers::flatc)
else()
set(FLATC_TARGET flatc)
set(FLATC flatc)
@@ -226,6 +239,8 @@ function(flatbuffers_generate_headers)
"--include-prefix" ${FLATBUFFERS_GENERATE_HEADERS_INCLUDE_PREFIX})
endif()
set(generated_custom_commands)
# Create rules to generate the code for each schema.
foreach(schema ${FLATBUFFERS_GENERATE_HEADERS_SCHEMAS})
get_filename_component(filename ${schema} NAME_WE)
@@ -254,6 +269,7 @@ function(flatbuffers_generate_headers)
COMMENT "Building ${schema} flatbuffers...")
list(APPEND all_generated_header_files ${generated_include})
list(APPEND all_generated_source_files ${generated_source_file})
list(APPEND generated_custom_commands "${generated_include}" "${generated_source_file}")
# Geneate the binary flatbuffers schemas if instructed to.
if (NOT ${FLATBUFFERS_GENERATE_HEADERS_BINARY_SCHEMAS_DIR} STREQUAL "")
@@ -267,10 +283,17 @@ function(flatbuffers_generate_headers)
${schema}
DEPENDS ${FLATC_TARGET} ${schema}
WORKING_DIRECTORY "${working_dir}")
list(APPEND generated_custom_commands "${binary_schema}")
list(APPEND all_generated_binary_files ${binary_schema})
endif()
endforeach()
# Create an additional target as add_custom_command scope is only within same directory (CMakeFile.txt)
set(generate_target GENERATE_${FLATBUFFERS_GENERATE_HEADERS_TARGET})
add_custom_target(${generate_target} ALL
DEPENDS ${generated_custom_commands}
COMMENT "Generating flatbuffer target ${FLATBUFFERS_GENERATE_HEADERS_TARGET}")
# Set up interface library
add_library(${FLATBUFFERS_GENERATE_HEADERS_TARGET} INTERFACE)
target_sources(
@@ -365,6 +388,9 @@ function(flatbuffers_generate_binary_files)
if(FLATBUFFERS_FLATC_EXECUTABLE)
set(FLATC_TARGET "")
set(FLATC ${FLATBUFFERS_FLATC_EXECUTABLE})
elseif(TARGET flatbuffers::flatc)
set(FLATC_TARGET flatbuffers::flatc)
set(FLATC flatbuffers::flatc)
else()
set(FLATC_TARGET flatc)
set(FLATC flatc)

View File

@@ -1,778 +0,0 @@
# This was the legacy <root>/CMakeLists.txt that supported cmake version 2.8.12.
# It was originally copied on Jan 30 2022, and is conditionally included in the
# current <root>/CMakeLists.txt if the cmake version used is older than the new
# minimum version.
#
# Only add to this file to fix immediate issues or if a change cannot be made
# <root>/CMakeList.txt in a compatible way.
if (POLICY CMP0048)
cmake_policy(SET CMP0048 NEW)
if(CMAKE_VERSION VERSION_LESS 3.9)
project(FlatBuffers
VERSION 2.0.0
LANGUAGES CXX)
else()
project(FlatBuffers
DESCRIPTION "Flatbuffers serialization library"
VERSION 2.0.0
LANGUAGES CXX)
endif()
else()
project(FlatBuffers)
endif (POLICY CMP0048)
include(CMake/Version.cmake)
# generate compile_commands.json
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
# NOTE: Code coverage only works on Linux & OSX.
option(FLATBUFFERS_CODE_COVERAGE "Enable the code coverage build option." OFF)
option(FLATBUFFERS_BUILD_TESTS "Enable the build of tests and samples." ON)
option(FLATBUFFERS_INSTALL "Enable the installation of targets." ON)
option(FLATBUFFERS_BUILD_FLATLIB "Enable the build of the flatbuffers library"
ON)
option(FLATBUFFERS_BUILD_FLATC "Enable the build of the flatbuffers compiler"
ON)
option(FLATBUFFERS_STATIC_FLATC "Build flatbuffers compiler with -static flag"
OFF)
option(FLATBUFFERS_BUILD_FLATHASH "Enable the build of flathash" ON)
option(FLATBUFFERS_BUILD_BENCHMARKS "Enable the build of flatbenchmark. \"
Requires C++11."
OFF)
option(FLATBUFFERS_BUILD_GRPCTEST "Enable the build of grpctest" OFF)
option(FLATBUFFERS_BUILD_SHAREDLIB
"Enable the build of the flatbuffers shared library"
OFF)
option(FLATBUFFERS_LIBCXX_WITH_CLANG "Force libc++ when using Clang" ON)
# NOTE: Sanitizer check only works on Linux & OSX (gcc & llvm).
option(FLATBUFFERS_CODE_SANITIZE
"Add '-fsanitize' flags to 'flattests' and 'flatc' targets."
OFF)
option(FLATBUFFERS_PACKAGE_REDHAT
"Build an rpm using the 'package' target."
OFF)
option(FLATBUFFERS_PACKAGE_DEBIAN
"Build an deb using the 'package' target."
OFF)
option(FLATBUFFERS_BUILD_CPP17
"Enable the build of c++17 test target. \"
Requirements: Clang6, GCC7, MSVC2017 (_MSC_VER >= 1914) or higher."
OFF)
option(FLATBUFFERS_BUILD_LEGACY
"Run C++ code generator with '--cpp-std c++0x' switch."
OFF)
option(FLATBUFFERS_ENABLE_PCH
"Enable precompile headers support for 'flatbuffers' and 'flatc'. \"
Only work if CMake supports 'target_precompile_headers'. \"
This can speed up compilation time."
OFF)
option(FLATBUFFERS_SKIP_MONSTER_EXTRA
"Skip generating monster_extra.fbs that contains non-supported numerical\"
types." OFF)
option(FLATBUFFERS_OSX_BUILD_UNIVERSAL
"Enable the build for multiple architectures on OS X (arm64, x86_64)."
ON)
if(NOT FLATBUFFERS_BUILD_FLATC AND FLATBUFFERS_BUILD_TESTS)
message(WARNING
"Cannot build tests without building the compiler. Tests will be disabled.")
set(FLATBUFFERS_BUILD_TESTS OFF)
endif()
if(DEFINED FLATBUFFERS_MAX_PARSING_DEPTH)
# Override the default recursion depth limit.
add_definitions(-DFLATBUFFERS_MAX_PARSING_DEPTH=${FLATBUFFERS_MAX_PARSING_DEPTH})
message(STATUS "FLATBUFFERS_MAX_PARSING_DEPTH: ${FLATBUFFERS_MAX_PARSING_DEPTH}")
endif()
# Auto-detect locale-narrow 'strtod_l' and 'strtoull_l' functions.
if(NOT DEFINED FLATBUFFERS_LOCALE_INDEPENDENT)
include(CheckCXXSymbolExists)
set(FLATBUFFERS_LOCALE_INDEPENDENT 0)
if(MSVC)
check_cxx_symbol_exists(_strtof_l stdlib.h FLATBUFFERS_HAS_STRTOF_L)
check_cxx_symbol_exists(_strtoui64_l stdlib.h FLATBUFFERS_HAS_STRTOULL_L)
else()
check_cxx_symbol_exists(strtof_l stdlib.h FLATBUFFERS_HAS_STRTOF_L)
check_cxx_symbol_exists(strtoull_l stdlib.h FLATBUFFERS_HAS_STRTOULL_L)
endif()
if(FLATBUFFERS_HAS_STRTOF_L AND FLATBUFFERS_HAS_STRTOULL_L)
set(FLATBUFFERS_LOCALE_INDEPENDENT 1)
endif()
endif()
add_definitions(-DFLATBUFFERS_LOCALE_INDEPENDENT=$<BOOL:${FLATBUFFERS_LOCALE_INDEPENDENT}>)
set(FlatBuffers_Library_SRCS
include/flatbuffers/allocator.h
include/flatbuffers/array.h
include/flatbuffers/base.h
include/flatbuffers/bfbs_generator.h
include/flatbuffers/buffer.h
include/flatbuffers/buffer_ref.h
include/flatbuffers/default_allocator.h
include/flatbuffers/detached_buffer.h
include/flatbuffers/flatbuffer_builder.h
include/flatbuffers/flatbuffers.h
include/flatbuffers/flexbuffers.h
include/flatbuffers/hash.h
include/flatbuffers/idl.h
include/flatbuffers/minireflect.h
include/flatbuffers/reflection.h
include/flatbuffers/reflection_generated.h
include/flatbuffers/registry.h
include/flatbuffers/stl_emulation.h
include/flatbuffers/string.h
include/flatbuffers/struct.h
include/flatbuffers/table.h
include/flatbuffers/util.h
include/flatbuffers/vector.h
include/flatbuffers/vector_downward.h
include/flatbuffers/verifier.h
src/idl_parser.cpp
src/idl_gen_text.cpp
src/reflection.cpp
src/util.cpp
)
set(FlatBuffers_Compiler_SRCS
${FlatBuffers_Library_SRCS}
src/idl_gen_cpp.cpp
src/idl_gen_csharp.cpp
src/idl_gen_dart.cpp
src/idl_gen_kotlin.cpp
src/idl_gen_go.cpp
src/idl_gen_java.cpp
src/idl_gen_ts.cpp
src/idl_gen_php.cpp
src/idl_gen_python.cpp
src/idl_gen_lobster.cpp
src/idl_gen_lua.cpp
src/idl_gen_rust.cpp
src/idl_gen_fbs.cpp
src/idl_gen_grpc.cpp
src/idl_gen_json_schema.cpp
src/idl_gen_swift.cpp
src/flatc.cpp
src/flatc_main.cpp
src/bfbs_gen.h
src/bfbs_gen_lua.h
include/flatbuffers/code_generators.h
src/bfbs_gen_lua.cpp
src/code_generators.cpp
grpc/src/compiler/schema_interface.h
grpc/src/compiler/cpp_generator.h
grpc/src/compiler/cpp_generator.cc
grpc/src/compiler/go_generator.h
grpc/src/compiler/go_generator.cc
grpc/src/compiler/java_generator.h
grpc/src/compiler/java_generator.cc
grpc/src/compiler/python_generator.h
grpc/src/compiler/python_generator.cc
grpc/src/compiler/swift_generator.h
grpc/src/compiler/swift_generator.cc
grpc/src/compiler/ts_generator.h
grpc/src/compiler/ts_generator.cc
)
set(FlatHash_SRCS
include/flatbuffers/hash.h
src/flathash.cpp
)
set(FlatBuffers_Tests_SRCS
${FlatBuffers_Library_SRCS}
src/idl_gen_fbs.cpp
tests/test.cpp
tests/test_assert.h
tests/test_assert.cpp
tests/test_builder.h
tests/test_builder.cpp
tests/native_type_test_impl.h
tests/native_type_test_impl.cpp
include/flatbuffers/code_generators.h
src/code_generators.cpp
# file generate by running compiler on tests/monster_test.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_generated.h
# file generate by running compiler on namespace_test/namespace_test1.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/namespace_test/namespace_test1_generated.h
${CMAKE_CURRENT_BINARY_DIR}/tests/namespace_test/namespace_test2_generated.h
# file generate by running compiler on union_vector/union_vector.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/union_vector/union_vector_generated.h
# file generate by running compiler on tests/arrays_test.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/arrays_test_generated.h
# file generate by running compiler on tests/native_type_test.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/native_type_test_generated.h
# file generate by running compiler on tests/monster_extra.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/monster_extra_generated.h
# file generate by running compiler on tests/monster_test.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_bfbs_generated.h
# file generate by running compiler on tests/optional_scalars.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/optional_scalars_generated.h
)
set(FlatBuffers_Tests_CPP17_SRCS
${FlatBuffers_Library_SRCS}
tests/test_assert.h
tests/test_assert.cpp
tests/cpp17/test_cpp17.cpp
# file generate by running compiler on tests/monster_test.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/cpp17/generated_cpp17/monster_test_generated.h
${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_generated.h
${CMAKE_CURRENT_BINARY_DIR}/tests/cpp17/generated_cpp17/optional_scalars_generated.h
${CMAKE_CURRENT_BINARY_DIR}/tests/optional_scalars_generated.h
)
set(FlatBuffers_Sample_Binary_SRCS
include/flatbuffers/flatbuffers.h
samples/sample_binary.cpp
# file generated by running compiler on samples/monster.fbs
${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h
)
set(FlatBuffers_Sample_Text_SRCS
${FlatBuffers_Library_SRCS}
samples/sample_text.cpp
# file generated by running compiler on samples/monster.fbs
${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h
)
set(FlatBuffers_Sample_BFBS_SRCS
${FlatBuffers_Library_SRCS}
samples/sample_bfbs.cpp
# file generated by running compiler on samples/monster.fbs
${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h
)
set(FlatBuffers_GRPCTest_SRCS
include/flatbuffers/flatbuffers.h
include/flatbuffers/grpc.h
include/flatbuffers/util.h
src/util.cpp
tests/monster_test.grpc.fb.h
tests/test_assert.h
tests/test_builder.h
tests/monster_test.grpc.fb.cc
tests/test_assert.cpp
tests/test_builder.cpp
grpc/tests/grpctest.cpp
grpc/tests/message_builder_test.cpp
# file generate by running compiler on tests/monster_test.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_generated.h
)
# source_group(Compiler FILES ${FlatBuffers_Compiler_SRCS})
# source_group(Tests FILES ${FlatBuffers_Tests_SRCS})
if(EXISTS "${CMAKE_TOOLCHAIN_FILE}")
# do not apply any global settings if the toolchain
# is being configured externally
message(STATUS "Using toolchain file: ${CMAKE_TOOLCHAIN_FILE}.")
elseif(CMAKE_COMPILER_IS_GNUCXX)
if(CYGWIN)
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -std=gnu++11")
else(CYGWIN)
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -std=c++0x")
endif(CYGWIN)
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -Wall -pedantic -Werror -Wextra -Werror=shadow")
set(FLATBUFFERS_PRIVATE_CXX_FLAGS "-Wold-style-cast")
if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 4.4)
if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 7.0)
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -faligned-new -Werror=implicit-fallthrough=2")
endif()
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -Wunused-result -Werror=unused-result -Wunused-parameter -Werror=unused-parameter")
endif()
# Certain platforms such as ARM do not use signed chars by default
# which causes issues with certain bounds checks.
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -fsigned-char")
# MSVC **MUST** come before the Clang check, as clang-cl is flagged by CMake as "MSVC", but it still textually
# matches as Clang in its Compiler Id :)
# Note: in CMake >= 3.14 we can check CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "GNU" or "MSVC" to differentiate...
elseif(MSVC)
# Visual Studio pedantic build settings
# warning C4512: assignment operator could not be generated
# warning C4316: object allocated on the heap may not be aligned
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W4 /WX /wd4512 /wd4316")
if(${CMAKE_CXX_COMPILER_ID} MATCHES "Clang")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /D_CRT_SECURE_NO_WARNINGS")
endif()
elseif(${CMAKE_CXX_COMPILER_ID} MATCHES "Clang")
if(APPLE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
if(FLATBUFFERS_OSX_BUILD_UNIVERSAL)
set(CMAKE_OSX_ARCHITECTURES "arm64;x86_64")
endif()
else()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
endif()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -pedantic -Werror -Wextra -Wno-unused-parameter")
set(FLATBUFFERS_PRIVATE_CXX_FLAGS "-Wold-style-cast")
if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.8)
list(APPEND FLATBUFFERS_PRIVATE_CXX_FLAGS "-Wimplicit-fallthrough" "-Wextra-semi" "-Werror=unused-private-field") # enable warning
endif()
if(FLATBUFFERS_LIBCXX_WITH_CLANG)
if(NOT "${CMAKE_SYSTEM_NAME}" MATCHES "Linux")
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -stdlib=libc++")
endif()
if(NOT ("${CMAKE_SYSTEM_NAME}" MATCHES "FreeBSD" OR
"${CMAKE_SYSTEM_NAME}" MATCHES "Linux"))
set(CMAKE_EXE_LINKER_FLAGS
"${CMAKE_EXE_LINKER_FLAGS} -lc++abi")
endif()
endif()
# Certain platforms such as ARM do not use signed chars by default
# which causes issues with certain bounds checks.
set(CMAKE_CXX_FLAGS
"${CMAKE_CXX_FLAGS} -fsigned-char")
endif()
# Append FLATBUFFERS_CXX_FLAGS to CMAKE_CXX_FLAGS.
if(DEFINED FLATBUFFERS_CXX_FLAGS AND NOT EXISTS "${CMAKE_TOOLCHAIN_FILE}")
message(STATUS "extend CXX_FLAGS with ${FLATBUFFERS_CXX_FLAGS}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${FLATBUFFERS_CXX_FLAGS}")
endif()
message(STATUS "CMAKE_CXX_FLAGS: ${CMAKE_CXX_FLAGS}")
if(FLATBUFFERS_CODE_COVERAGE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -fprofile-arcs -ftest-coverage")
set(CMAKE_EXE_LINKER_FLAGS
"${CMAKE_EXE_LINKER_FLAGS} -fprofile-arcs -ftest-coverage")
endif()
function(add_fsanitize_to_target _target _sanitizer)
if(WIN32)
target_compile_definitions(${_target} PRIVATE FLATBUFFERS_MEMORY_LEAK_TRACKING)
message(STATUS "Sanitizer MSVC::_CrtDumpMemoryLeaks added to ${_target}")
else()
# FLATBUFFERS_CODE_SANITIZE: boolean {ON,OFF,YES,NO} or string with list of sanitizer.
# List of sanitizer is string starts with '=': "=address,undefined,thread,memory".
if((${CMAKE_CXX_COMPILER_ID} MATCHES "Clang") OR
((${CMAKE_CXX_COMPILER_ID} MATCHES "GNU") AND NOT (CMAKE_CXX_COMPILER_VERSION VERSION_LESS "4.9"))
)
set(_sanitizer_flags "=address,undefined")
if(_sanitizer MATCHES "=.*")
# override default by user-defined sanitizer list
set(_sanitizer_flags ${_sanitizer})
endif()
target_compile_options(${_target} PRIVATE
-g -fsigned-char -fno-omit-frame-pointer
"-fsanitize${_sanitizer_flags}")
target_link_libraries(${_target} PRIVATE
"-fsanitize${_sanitizer_flags}")
set_property(TARGET ${_target} PROPERTY POSITION_INDEPENDENT_CODE ON)
message(STATUS "Sanitizer ${_sanitizer_flags} added to ${_target}")
endif()
endif()
endfunction()
function(add_pch_to_target _target _pch_header)
if(COMMAND target_precompile_headers)
target_precompile_headers(${_target} PRIVATE ${_pch_header})
if(NOT MSVC)
set_source_files_properties(src/util.cpp PROPERTIES SKIP_PRECOMPILE_HEADERS ON)
endif()
endif()
endfunction()
if(BIICODE)
include(biicode/cmake/biicode.cmake)
return()
endif()
include_directories(include)
include_directories(grpc)
if(FLATBUFFERS_BUILD_FLATLIB)
add_library(flatbuffers STATIC ${FlatBuffers_Library_SRCS})
# Attach header directory for when build via add_subdirectory().
target_include_directories(flatbuffers INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>)
target_compile_options(flatbuffers PRIVATE "${FLATBUFFERS_PRIVATE_CXX_FLAGS}")
if(FLATBUFFERS_ENABLE_PCH)
add_pch_to_target(flatbuffers include/flatbuffers/pch/pch.h)
endif()
endif()
if(FLATBUFFERS_BUILD_FLATC)
add_executable(flatc ${FlatBuffers_Compiler_SRCS})
if(FLATBUFFERS_ENABLE_PCH)
add_pch_to_target(flatc include/flatbuffers/pch/flatc_pch.h)
endif()
target_compile_options(flatc PRIVATE "${FLATBUFFERS_PRIVATE_CXX_FLAGS}")
if(FLATBUFFERS_CODE_SANITIZE AND NOT WIN32)
add_fsanitize_to_target(flatc ${FLATBUFFERS_CODE_SANITIZE})
endif()
if(NOT FLATBUFFERS_FLATC_EXECUTABLE)
set(FLATBUFFERS_FLATC_EXECUTABLE $<TARGET_FILE:flatc>)
endif()
if(MSVC)
# Make flatc.exe not depend on runtime dlls for easy distribution.
target_compile_options(flatc PUBLIC $<$<CONFIG:Release>:/MT>)
endif()
if(FLATBUFFERS_STATIC_FLATC AND NOT MSVC)
target_link_libraries(flatc PRIVATE -static)
endif()
endif()
if(FLATBUFFERS_BUILD_FLATHASH)
add_executable(flathash ${FlatHash_SRCS})
endif()
if(FLATBUFFERS_BUILD_SHAREDLIB)
add_library(flatbuffers_shared SHARED ${FlatBuffers_Library_SRCS})
# FlatBuffers use calendar-based versioning and do not provide any ABI
# stability guarantees. Therefore, always use the full version as SOVERSION
# in order to avoid breaking reverse dependencies on upgrades.
set(FlatBuffers_Library_SONAME_FULL "${PROJECT_VERSION}")
set_target_properties(flatbuffers_shared PROPERTIES OUTPUT_NAME flatbuffers
SOVERSION "${FlatBuffers_Library_SONAME_FULL}"
VERSION "${FlatBuffers_Library_SONAME_FULL}")
if(FLATBUFFERS_ENABLE_PCH)
add_pch_to_target(flatbuffers_shared include/flatbuffers/pch/pch.h)
endif()
endif()
# Global list of generated files.
# Use the global property to be independent of PARENT_SCOPE.
set_property(GLOBAL PROPERTY FBS_GENERATED_OUTPUTS)
function(get_generated_output generated_files)
get_property(tmp GLOBAL PROPERTY FBS_GENERATED_OUTPUTS)
set(${generated_files} ${tmp} PARENT_SCOPE)
endfunction(get_generated_output)
function(register_generated_output file_name)
get_property(tmp GLOBAL PROPERTY FBS_GENERATED_OUTPUTS)
list(APPEND tmp ${file_name})
set_property(GLOBAL PROPERTY FBS_GENERATED_OUTPUTS ${tmp})
endfunction(register_generated_output)
function(compile_flatbuffers_schema_to_cpp_opt SRC_FBS OPT)
if(FLATBUFFERS_BUILD_LEGACY)
set(OPT ${OPT};--cpp-std c++0x)
else()
# --cpp-std is defined by flatc default settings.
endif()
message(STATUS "`${SRC_FBS}`: add generation of C++ code with '${OPT}'")
get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH)
string(REGEX REPLACE "\\.fbs$" "_generated.h" GEN_HEADER ${SRC_FBS})
add_custom_command(
OUTPUT ${GEN_HEADER}
COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}"
--cpp --gen-mutable --gen-object-api --reflect-names
--cpp-ptr-type flatbuffers::unique_ptr # Used to test with C++98 STLs
${OPT}
-I "${CMAKE_CURRENT_SOURCE_DIR}/tests/include_test"
-o "${SRC_FBS_DIR}"
"${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}"
DEPENDS flatc
COMMENT "Run generation: '${GEN_HEADER}'")
register_generated_output(${GEN_HEADER})
endfunction()
function(compile_flatbuffers_schema_to_cpp SRC_FBS)
compile_flatbuffers_schema_to_cpp_opt(${SRC_FBS} "--no-includes;--gen-compare")
endfunction()
function(compile_flatbuffers_schema_to_binary SRC_FBS)
message(STATUS "`${SRC_FBS}`: add generation of binary (.bfbs) schema")
get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH)
string(REGEX REPLACE "\\.fbs$" ".bfbs" GEN_BINARY_SCHEMA ${SRC_FBS})
# For details about flags see generate_code.py
add_custom_command(
OUTPUT ${GEN_BINARY_SCHEMA}
COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}"
-b --schema --bfbs-comments --bfbs-builtins
--bfbs-filenames ${SRC_FBS_DIR}
-I "${CMAKE_CURRENT_SOURCE_DIR}/tests/include_test"
-o "${SRC_FBS_DIR}"
"${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}"
DEPENDS flatc
COMMENT "Run generation: '${GEN_BINARY_SCHEMA}'")
register_generated_output(${GEN_BINARY_SCHEMA})
endfunction()
function(compile_flatbuffers_schema_to_embedded_binary SRC_FBS OPT)
if(FLATBUFFERS_BUILD_LEGACY)
set(OPT ${OPT};--cpp-std c++0x)
else()
# --cpp-std is defined by flatc default settings.
endif()
message(STATUS "`${SRC_FBS}`: add generation of C++ embedded binary schema code with '${OPT}'")
get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH)
string(REGEX REPLACE "\\.fbs$" "_bfbs_generated.h" GEN_BFBS_HEADER ${SRC_FBS})
# For details about flags see generate_code.py
add_custom_command(
OUTPUT ${GEN_BFBS_HEADER}
COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}"
--cpp --gen-mutable --gen-object-api --reflect-names
--cpp-ptr-type flatbuffers::unique_ptr # Used to test with C++98 STLs
${OPT}
--bfbs-comments --bfbs-builtins --bfbs-gen-embed
--bfbs-filenames ${SRC_FBS_DIR}
-I "${CMAKE_CURRENT_SOURCE_DIR}/tests/include_test"
-o "${SRC_FBS_DIR}"
"${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}"
DEPENDS flatc
COMMENT "Run generation: '${GEN_BFBS_HEADER}'")
register_generated_output(${GEN_BFBS_HEADER})
endfunction()
# Look if we have python 3.5 installed so that we can run the generate code
# python script after flatc is built.
find_package(PythonInterp 3.5)
if(PYTHONINTERP_FOUND AND
# Skip doing this if the MSVC version is below VS 12.
# https://cmake.org/cmake/help/latest/variable/MSVC_VERSION.html
(NOT MSVC OR MSVC_VERSION GREATER 1800))
set(GENERATION_SCRIPT ${PYTHON_EXECUTABLE} scripts/generate_code.py)
if(FLATBUFFERS_BUILD_LEGACY)
# Need to set --cpp-std c++-0x options
set(GENERATION_SCRIPT ${GENERATION_SCRIPT} --cpp-0x)
endif()
if(FLATBUFFERS_SKIP_MONSTER_EXTRA)
set(GENERATION_SCRIPT ${GENERATION_SCRIPT} --skip-monster-extra)
endif()
add_custom_command(
TARGET flatc
POST_BUILD
COMMAND ${GENERATION_SCRIPT} --flatc "${FLATBUFFERS_FLATC_EXECUTABLE}"
WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
COMMENT "Running ${GENERATION_SCRIPT}..."
VERBATIM)
else()
message("No Python3 interpreter found! Unable to generate files automatically.")
endif()
if(FLATBUFFERS_BUILD_TESTS)
file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/tests" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}")
file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/samples" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}")
# TODO Add (monster_test.fbs monsterdata_test.json)->monsterdata_test.mon
compile_flatbuffers_schema_to_cpp(tests/monster_test.fbs)
compile_flatbuffers_schema_to_binary(tests/monster_test.fbs)
compile_flatbuffers_schema_to_cpp_opt(tests/namespace_test/namespace_test1.fbs "--no-includes;--gen-compare;--gen-name-strings")
compile_flatbuffers_schema_to_cpp_opt(tests/namespace_test/namespace_test2.fbs "--no-includes;--gen-compare;--gen-name-strings")
compile_flatbuffers_schema_to_cpp_opt(tests/union_vector/union_vector.fbs "--no-includes;--gen-compare;--gen-name-strings")
compile_flatbuffers_schema_to_cpp(tests/optional_scalars.fbs)
compile_flatbuffers_schema_to_cpp_opt(tests/native_type_test.fbs "")
compile_flatbuffers_schema_to_cpp_opt(tests/arrays_test.fbs "--scoped-enums;--gen-compare")
compile_flatbuffers_schema_to_binary(tests/arrays_test.fbs)
compile_flatbuffers_schema_to_embedded_binary(tests/monster_test.fbs "--no-includes;--gen-compare")
if(NOT (MSVC AND (MSVC_VERSION LESS 1900)))
compile_flatbuffers_schema_to_cpp(tests/monster_extra.fbs) # Test floating-point NAN/INF.
endif()
include_directories(${CMAKE_CURRENT_BINARY_DIR}/tests)
add_executable(flattests ${FlatBuffers_Tests_SRCS})
add_dependencies(flattests generated_code)
set_property(TARGET flattests
PROPERTY COMPILE_DEFINITIONS FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
FLATBUFFERS_DEBUG_VERIFICATION_FAILURE=1)
if(FLATBUFFERS_CODE_SANITIZE)
add_fsanitize_to_target(flattests ${FLATBUFFERS_CODE_SANITIZE})
endif()
compile_flatbuffers_schema_to_cpp(samples/monster.fbs)
compile_flatbuffers_schema_to_binary(samples/monster.fbs)
include_directories(${CMAKE_CURRENT_BINARY_DIR}/samples)
add_executable(flatsamplebinary ${FlatBuffers_Sample_Binary_SRCS})
add_dependencies(flatsamplebinary generated_code)
add_executable(flatsampletext ${FlatBuffers_Sample_Text_SRCS})
add_dependencies(flatsampletext generated_code)
add_executable(flatsamplebfbs ${FlatBuffers_Sample_BFBS_SRCS})
add_dependencies(flatsamplebfbs generated_code)
if(FLATBUFFERS_BUILD_CPP17)
# Don't generate header for flattests_cpp17 target.
# This target uses "generated_cpp17/monster_test_generated.h"
# produced by direct call of generate_code.py script.
add_executable(flattests_cpp17 ${FlatBuffers_Tests_CPP17_SRCS})
add_dependencies(flattests_cpp17 generated_code)
target_compile_features(flattests_cpp17 PRIVATE cxx_std_17)
target_compile_definitions(flattests_cpp17 PRIVATE
FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
FLATBUFFERS_DEBUG_VERIFICATION_FAILURE=1
)
if(FLATBUFFERS_CODE_SANITIZE)
add_fsanitize_to_target(flattests_cpp17 ${FLATBUFFERS_CODE_SANITIZE})
endif()
endif(FLATBUFFERS_BUILD_CPP17)
endif()
if(FLATBUFFERS_BUILD_GRPCTEST)
if(CMAKE_COMPILER_IS_GNUCXX)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-parameter -Wno-shadow")
endif()
if(NOT GRPC_INSTALL_PATH)
message(SEND_ERROR "GRPC_INSTALL_PATH variable is not defined. See grpc/README.md")
endif()
if(NOT PROTOBUF_DOWNLOAD_PATH)
message(SEND_ERROR "PROTOBUF_DOWNLOAD_PATH variable is not defined. See grpc/README.md")
endif()
INCLUDE_DIRECTORIES(${GRPC_INSTALL_PATH}/include)
INCLUDE_DIRECTORIES(${PROTOBUF_DOWNLOAD_PATH}/src)
find_package(Threads REQUIRED)
list(APPEND CMAKE_PREFIX_PATH ${GRPC_INSTALL_PATH})
find_package(absl CONFIG REQUIRED)
find_package(protobuf CONFIG REQUIRED)
find_package(gRPC CONFIG REQUIRED)
add_executable(grpctest ${FlatBuffers_GRPCTest_SRCS})
add_dependencies(grpctest generated_code)
target_link_libraries(grpctest PRIVATE gRPC::grpc++_unsecure gRPC::grpc_unsecure gRPC::gpr pthread dl)
if(FLATBUFFERS_CODE_SANITIZE AND NOT WIN32)
# GRPC test has problems with alignment and will fail under ASAN/UBSAN.
# add_fsanitize_to_target(grpctest ${FLATBUFFERS_CODE_SANITIZE})
endif()
endif()
if(FLATBUFFERS_INSTALL)
include(GNUInstallDirs)
install(DIRECTORY include/flatbuffers DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
set(FB_CMAKE_DIR "${CMAKE_INSTALL_LIBDIR}/cmake/flatbuffers")
configure_file(CMake/flatbuffers-config-version.cmake.in flatbuffers-config-version.cmake @ONLY)
install(
FILES "CMake/flatbuffers-config.cmake" "${CMAKE_CURRENT_BINARY_DIR}/flatbuffers-config-version.cmake"
DESTINATION ${FB_CMAKE_DIR}
)
if(FLATBUFFERS_BUILD_FLATLIB)
if(CMAKE_VERSION VERSION_LESS 3.0)
install(
TARGETS flatbuffers EXPORT FlatBuffersTargets
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
)
else()
install(
TARGETS flatbuffers EXPORT FlatBuffersTargets
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)
endif()
install(EXPORT FlatBuffersTargets
FILE FlatBuffersTargets.cmake
NAMESPACE flatbuffers::
DESTINATION ${FB_CMAKE_DIR}
)
endif()
if(FLATBUFFERS_BUILD_FLATC)
install(
TARGETS flatc EXPORT FlatcTargets
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
install(
EXPORT FlatcTargets
FILE FlatcTargets.cmake
NAMESPACE flatbuffers::
DESTINATION ${FB_CMAKE_DIR}
)
endif()
if(FLATBUFFERS_BUILD_SHAREDLIB)
if(CMAKE_VERSION VERSION_LESS 3.0)
install(
TARGETS flatbuffers_shared EXPORT FlatBuffersSharedTargets
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
)
else()
install(
TARGETS flatbuffers_shared EXPORT FlatBuffersSharedTargets
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)
endif()
install(
EXPORT FlatBuffersSharedTargets
FILE FlatBuffersSharedTargets.cmake
NAMESPACE flatbuffers::
DESTINATION ${FB_CMAKE_DIR}
)
endif()
if(FLATBUFFERS_BUILD_SHAREDLIB OR FLATBUFFERS_BUILD_FLATLIB)
configure_file(CMake/flatbuffers.pc.in flatbuffers.pc @ONLY)
install(
FILES "${CMAKE_CURRENT_BINARY_DIR}/flatbuffers.pc"
DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig
)
endif()
endif()
if(FLATBUFFERS_BUILD_TESTS)
enable_testing()
add_test(NAME flattests COMMAND flattests)
if(FLATBUFFERS_BUILD_CPP17)
add_test(NAME flattests_cpp17 COMMAND flattests_cpp17)
endif()
if(FLATBUFFERS_BUILD_GRPCTEST)
add_test(NAME grpctest COMMAND grpctest)
endif()
endif()
# This target is sync-barrier.
# Other generate-dependent targets can depend on 'generated_code' only.
get_generated_output(fbs_generated)
if(fbs_generated)
# message(STATUS "Add generated_code target with files:${fbs_generated}")
add_custom_target(generated_code
DEPENDS ${fbs_generated}
COMMENT "All generated files were updated.")
endif()
include(CMake/BuildFlatBuffers.cmake)
if(UNIX)
# Use of CPack only supported on Linux systems.
if(FLATBUFFERS_PACKAGE_DEBIAN)
include(CMake/PackageDebian.cmake)
include(CPack)
endif()
if (FLATBUFFERS_PACKAGE_REDHAT)
include(CMake/PackageRedhat.cmake)
include(CPack)
endif()
endif()
# Include for running Google Benchmarks.
if(FLATBUFFERS_BUILD_BENCHMARKS AND CMAKE_VERSION VERSION_GREATER 3.13)
add_subdirectory(benchmarks)
endif()
# Add FlatBuffers::FlatBuffers interface, needed for FetchContent_Declare
add_library(FlatBuffers INTERFACE)
add_library(FlatBuffers::FlatBuffers ALIAS FlatBuffers)
target_include_directories(
FlatBuffers
INTERFACE $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}/include>)

View File

@@ -17,23 +17,9 @@ if (UNIX)
SET(CPACK_PACKAGE_VERSION "${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}-${VERSION_COMMIT}")
SET(CPACK_DEBIAN_PACKAGE_VERSION "${CPACK_PACKAGE_VERSION}")
# Derive architecture
IF(NOT CPACK_DEBIAN_PACKAGE_ARCHITECTURE)
FIND_PROGRAM(DPKG_CMD dpkg)
IF(NOT DPKG_CMD)
MESSAGE(STATUS "Can not find dpkg in your path, default to i386.")
SET(CPACK_DEBIAN_PACKAGE_ARCHITECTURE i386)
ENDIF(NOT DPKG_CMD)
EXECUTE_PROCESS(COMMAND "${DPKG_CMD}" --print-architecture
OUTPUT_VARIABLE CPACK_DEBIAN_PACKAGE_ARCHITECTURE
OUTPUT_STRIP_TRAILING_WHITESPACE
)
ENDIF(NOT CPACK_DEBIAN_PACKAGE_ARCHITECTURE)
# Package name
SET(CPACK_DEBIAN_PACKAGE_NAME "flatbuffers")
SET(CPACK_RESOURCE_FILE_LICENSE ${CMAKE_SOURCE_DIR}/LICENSE.txt)
SET(CPACK_PACKAGE_FILE_NAME
"${CPACK_DEBIAN_PACKAGE_NAME}_${CPACK_DEBIAN_PACKAGE_VERSION}_${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}")
SET(CPACK_RESOURCE_FILE_LICENSE ${CMAKE_SOURCE_DIR}/LICENSE)
set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT")
endif(UNIX)

View File

@@ -15,14 +15,14 @@ if (UNIX)
set(CPACK_RPM_PACKAGE_NAME "flatbuffers")
# Assume this is not a cross complation build.
# Assume this is not a cross compilation build.
if(NOT CPACK_RPM_PACKAGE_ARCHITECTURE)
set(CPACK_RPM_PACKAGE_ARCHITECTURE "${CMAKE_SYSTEM_PROCESSOR}")
endif(NOT CPACK_RPM_PACKAGE_ARCHITECTURE)
set(CPACK_RPM_PACKAGE_VENDOR "Google, Inc.")
set(CPACK_RPM_PACKAGE_LICENSE "Apache 2.0")
set(CPACK_RESOURCE_FILE_LICENSE ${CMAKE_SOURCE_DIR}/LICENSE.txt)
set(CPACK_RESOURCE_FILE_LICENSE ${CMAKE_SOURCE_DIR}/LICENSE)
set(CPACK_PACKAGE_DESCRIPTION_FILE ${CMAKE_SOURCE_DIR}/CMake/DESCRIPTION.txt)
# This may reduce rpm compatiblity with very old systems.

View File

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

View File

@@ -1,3 +1,4 @@
include("${CMAKE_CURRENT_LIST_DIR}/FlatBuffersTargets.cmake" OPTIONAL)
include("${CMAKE_CURRENT_LIST_DIR}/FlatcTargets.cmake" OPTIONAL)
include("${CMAKE_CURRENT_LIST_DIR}/FlatBuffersSharedTargets.cmake" OPTIONAL)
include("${CMAKE_CURRENT_LIST_DIR}/BuildFlatBuffers.cmake" OPTIONAL)

View File

@@ -1,32 +1,12 @@
# This is the legacy minimum version flatbuffers supported for a while.
cmake_minimum_required(VERSION 2.8.12...3.22.1)
# CMake version 3.16 is the 'de-facto' minimum version for flatbuffers. If the
# current cmake is older than this, warn the user and include the legacy file to
# provide some level of support.
if(CMAKE_VERSION VERSION_LESS 3.16)
message(WARNING "Using cmake version ${CMAKE_VERSION} which is older than "
"our target version of 3.16. This will use the legacy CMakeLists.txt that "
"supports version 2.8.12 and higher, but not actively maintained. Consider "
"upgrading cmake to a newer version, as this may become a fatal error in the "
"future.")
# Use the legacy version of CMakeLists.txt
include(CMake/CMakeLists_legacy.cmake.in)
return()
endif()
cmake_minimum_required(VERSION 3.8...3.25.2)
# Attempt to read the current version of flatbuffers by looking at the latest tag.
include(CMake/Version.cmake)
if (POLICY CMP0048)
cmake_policy(SET CMP0048 NEW)
project(FlatBuffers
DESCRIPTION "Flatbuffers serialization library"
project(FlatBuffers
VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}
LANGUAGES CXX)
else()
project(FlatBuffers)
endif (POLICY CMP0048)
# generate compile_commands.json
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
@@ -41,7 +21,7 @@ option(FLATBUFFERS_BUILD_FLATC "Enable the build of the flatbuffers compiler"
ON)
option(FLATBUFFERS_STATIC_FLATC "Build flatbuffers compiler with -static flag"
OFF)
option(FLATBUFFERS_BUILD_FLATHASH "Enable the build of flathash" ON)
option(FLATBUFFERS_BUILD_FLATHASH "Enable the build of flathash" OFF)
option(FLATBUFFERS_BUILD_BENCHMARKS "Enable the build of flatbenchmark."
OFF)
option(FLATBUFFERS_BUILD_GRPCTEST "Enable the build of grpctest" OFF)
@@ -87,6 +67,12 @@ if(MSVC OR CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "MSVC")
set(MSVC_LIKE ON)
endif()
if(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
set(IS_CLANG ON)
else()
set(IS_CLANG OFF)
endif()
if(DEFINED FLATBUFFERS_COMPILATION_TIMINGS)
message("Recording Compilation Timings to ${FLATBUFFERS_COMPILATION_TIMINGS}")
file(REMOVE ${FLATBUFFERS_COMPILATION_TIMINGS})
@@ -136,12 +122,12 @@ set(FlatBuffers_Library_SRCS
include/flatbuffers/allocator.h
include/flatbuffers/array.h
include/flatbuffers/base.h
include/flatbuffers/bfbs_generator.h
include/flatbuffers/buffer.h
include/flatbuffers/buffer_ref.h
include/flatbuffers/default_allocator.h
include/flatbuffers/detached_buffer.h
include/flatbuffers/code_generator.h
include/flatbuffers/file_manager.h
include/flatbuffers/flatbuffer_builder.h
include/flatbuffers/flatbuffers.h
include/flatbuffers/flexbuffers.h
@@ -168,6 +154,8 @@ set(FlatBuffers_Library_SRCS
set(FlatBuffers_Compiler_SRCS
${FlatBuffers_Library_SRCS}
src/idl_gen_binary.cpp
src/idl_gen_text.cpp
src/idl_gen_cpp.cpp
src/idl_gen_csharp.cpp
src/idl_gen_dart.cpp
@@ -178,12 +166,14 @@ set(FlatBuffers_Compiler_SRCS
src/idl_gen_php.cpp
src/idl_gen_python.cpp
src/idl_gen_lobster.cpp
src/idl_gen_lua.cpp
src/idl_gen_rust.cpp
src/idl_gen_fbs.cpp
src/idl_gen_grpc.cpp
src/idl_gen_json_schema.cpp
src/idl_gen_swift.cpp
src/file_name_saving_file_manager.cpp
src/file_binary_writer.cpp
src/file_writer.cpp
src/idl_namer.h
src/namer.h
src/flatc.cpp
@@ -243,31 +233,10 @@ set(FlatBuffers_Tests_SRCS
tests/native_type_test_impl.cpp
tests/alignment_test.h
tests/alignment_test.cpp
tests/64bit/offset64_test.h
tests/64bit/offset64_test.cpp
include/flatbuffers/code_generators.h
src/code_generators.cpp
# file generate by running compiler on tests/monster_test.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_generated.h
# file generate by running compiler on namespace_test/namespace_test1.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/namespace_test/namespace_test1_generated.h
${CMAKE_CURRENT_BINARY_DIR}/tests/namespace_test/namespace_test2_generated.h
# file generate by running compiler on union_vector/union_vector.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/union_vector/union_vector_generated.h
# file generate by running compiler on tests/arrays_test.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/arrays_test_generated.h
# file generate by running compiler on tests/native_type_test.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/native_type_test_generated.h
# file generate by running compiler on tests/monster_extra.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/monster_extra_generated.h
# file generate by running compiler on tests/monster_test.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_bfbs_generated.h
# file generate by running compiler on tests/optional_scalars.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/optional_scalars_generated.h
# file generate by running compiler on tests/native_inline_table_test.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/native_inline_table_test_generated.h
# file generate by running compiler on tests/alignment_test.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/alignment_test_generated.h
# file generate by running compiler on tests/key_field/key_field_sample.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/key_field/key_field_sample_generated.h
)
set(FlatBuffers_Tests_CPP17_SRCS
@@ -275,32 +244,20 @@ set(FlatBuffers_Tests_CPP17_SRCS
tests/test_assert.h
tests/test_assert.cpp
tests/cpp17/test_cpp17.cpp
# file generate by running compiler on tests/monster_test.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/cpp17/generated_cpp17/monster_test_generated.h
${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_generated.h
${CMAKE_CURRENT_BINARY_DIR}/tests/cpp17/generated_cpp17/optional_scalars_generated.h
${CMAKE_CURRENT_BINARY_DIR}/tests/optional_scalars_generated.h
)
set(FlatBuffers_Sample_Binary_SRCS
include/flatbuffers/flatbuffers.h
samples/sample_binary.cpp
# file generated by running compiler on samples/monster.fbs
${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h
)
set(FlatBuffers_Sample_Text_SRCS
${FlatBuffers_Library_SRCS}
samples/sample_text.cpp
# file generated by running compiler on samples/monster.fbs
${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h
)
set(FlatBuffers_Sample_BFBS_SRCS
${FlatBuffers_Library_SRCS}
samples/sample_bfbs.cpp
# file generated by running compiler on samples/monster.fbs
${CMAKE_CURRENT_BINARY_DIR}/samples/monster_generated.h
)
set(FlatBuffers_GRPCTest_SRCS
@@ -316,14 +273,12 @@ set(FlatBuffers_GRPCTest_SRCS
tests/test_builder.cpp
grpc/tests/grpctest.cpp
grpc/tests/message_builder_test.cpp
# file generate by running compiler on tests/monster_test.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/monster_test_generated.h
)
# TODO(dbaileychess): Figure out how this would now work. I posted a question on
# https://stackoverflow.com/questions/71772330/override-target-compile-options-via-cmake-command-line.
# Append FLATBUFFERS_CXX_FLAGS to CMAKE_CXX_FLAGS.
if(DEFINED FLATBUFFERS_CXX_FLAGS AND NOT EXISTS "${CMAKE_TOOLCHAIN_FILE}")
if(DEFINED FLATBUFFERS_CXX_FLAGS)
message(STATUS "extend CXX_FLAGS with ${FLATBUFFERS_CXX_FLAGS}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${FLATBUFFERS_CXX_FLAGS}")
endif()
@@ -336,9 +291,7 @@ function(add_fsanitize_to_target _target _sanitizer)
else()
# FLATBUFFERS_CODE_SANITIZE: boolean {ON,OFF,YES,NO} or string with list of sanitizer.
# List of sanitizer is string starts with '=': "=address,undefined,thread,memory".
if((${CMAKE_CXX_COMPILER_ID} MATCHES "Clang") OR
((${CMAKE_CXX_COMPILER_ID} MATCHES "GNU") AND NOT (CMAKE_CXX_COMPILER_VERSION VERSION_LESS "4.9"))
)
if(IS_CLANG OR (CMAKE_COMPILER_IS_GNUCXX AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 4.9))
set(_sanitizer_flags "=address,undefined")
if(_sanitizer MATCHES "=.*")
# override default by user-defined sanitizer list
@@ -349,13 +302,14 @@ function(add_fsanitize_to_target _target _sanitizer)
"-fsanitize${_sanitizer_flags}")
target_link_libraries(${_target} PRIVATE
"-fsanitize${_sanitizer_flags}")
set_property(TARGET ${_target} PROPERTY POSITION_INDEPENDENT_CODE ON)
set_target_properties(${_target} PROPERTIES POSITION_INDEPENDENT_CODE ON)
message(STATUS "Sanitizer ${_sanitizer_flags} added to ${_target}")
endif()
endif()
endfunction()
function(add_pch_to_target _target _pch_header)
# the command is available since cmake 3.16
if(COMMAND target_precompile_headers)
target_precompile_headers(${_target} PRIVATE ${_pch_header})
if(NOT MSVC)
@@ -399,11 +353,6 @@ if(MSVC_LIKE)
>
)
else()
if("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
set(IS_CLANG ON)
else()
set(IS_CLANG OFF)
endif()
target_compile_options(ProjectConfig
INTERFACE
-Wall
@@ -500,7 +449,7 @@ if(FLATBUFFERS_BUILD_FLATC)
target_link_libraries(flatc PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
target_compile_options(flatc
PUBLIC
PRIVATE
$<$<AND:$<BOOL:${MSVC_LIKE}>,$<CONFIG:Release>>:
/MT
>
@@ -529,7 +478,8 @@ if(FLATBUFFERS_BUILD_SHAREDLIB)
# stability guarantees. Therefore, always use the full version as SOVERSION
# in order to avoid breaking reverse dependencies on upgrades.
set(FlatBuffers_Library_SONAME_FULL "${PROJECT_VERSION}")
set_target_properties(flatbuffers_shared PROPERTIES OUTPUT_NAME flatbuffers
set_target_properties(flatbuffers_shared PROPERTIES
OUTPUT_NAME flatbuffers
SOVERSION "${FlatBuffers_Library_SONAME_FULL}"
VERSION "${FlatBuffers_Library_SONAME_FULL}")
if(FLATBUFFERS_ENABLE_PCH)
@@ -537,146 +487,89 @@ if(FLATBUFFERS_BUILD_SHAREDLIB)
endif()
endif()
# Global list of generated files.
# Use the global property to be independent of PARENT_SCOPE.
set_property(GLOBAL PROPERTY FBS_GENERATED_OUTPUTS)
function(get_generated_output generated_files)
get_property(tmp GLOBAL PROPERTY FBS_GENERATED_OUTPUTS)
set(${generated_files} ${tmp} PARENT_SCOPE)
endfunction(get_generated_output)
function(register_generated_output file_name)
get_property(tmp GLOBAL PROPERTY FBS_GENERATED_OUTPUTS)
list(APPEND tmp ${file_name})
set_property(GLOBAL PROPERTY FBS_GENERATED_OUTPUTS ${tmp})
endfunction(register_generated_output)
function(compile_flatbuffers_schema_to_cpp_opt SRC_FBS OPT)
if(FLATBUFFERS_BUILD_LEGACY)
set(OPT ${OPT};--cpp-std c++0x)
else()
# --cpp-std is defined by flatc default settings.
endif()
message(STATUS "`${SRC_FBS}`: add generation of C++ code with '${OPT}'")
function(compile_schema SRC_FBS OPT OUT_GEN_FILE)
get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH)
string(REGEX REPLACE "\\.fbs$" "_generated.h" GEN_HEADER ${SRC_FBS})
add_custom_command(
OUTPUT ${GEN_HEADER}
COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}"
--cpp --gen-mutable --gen-object-api --reflect-names
--cpp-ptr-type flatbuffers::unique_ptr # Used to test with C++98 STLs
${OPT}
-I "${CMAKE_CURRENT_SOURCE_DIR}/tests/include_test"
-o "${SRC_FBS_DIR}"
"${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}"
${OPT}
-o "${SRC_FBS_DIR}"
"${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}"
DEPENDS flatc
COMMENT "Run generation: '${GEN_HEADER}'")
register_generated_output(${GEN_HEADER})
COMMENT "flatc generation: `${SRC_FBS}` -> `${GEN_HEADER}`"
)
set(${OUT_GEN_FILE} ${GEN_HEADER} PARENT_SCOPE)
endfunction()
function(compile_flatbuffers_schema_to_cpp SRC_FBS)
compile_flatbuffers_schema_to_cpp_opt(${SRC_FBS} "--no-includes;--gen-compare")
function(compile_schema_for_test SRC_FBS OPT)
compile_schema("${SRC_FBS}" "${OPT}" GEN_FILE)
target_sources(flattests PRIVATE ${GEN_FILE})
endfunction()
function(compile_flatbuffers_schema_to_binary SRC_FBS)
message(STATUS "`${SRC_FBS}`: add generation of binary (.bfbs) schema")
get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH)
string(REGEX REPLACE "\\.fbs$" ".bfbs" GEN_BINARY_SCHEMA ${SRC_FBS})
# For details about flags see generate_code.py
add_custom_command(
OUTPUT ${GEN_BINARY_SCHEMA}
COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}"
-b --schema --bfbs-comments --bfbs-builtins
--bfbs-filenames "${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS_DIR}"
-I "${CMAKE_CURRENT_SOURCE_DIR}/tests/include_test"
-o "${SRC_FBS_DIR}"
"${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}"
DEPENDS flatc
COMMENT "Run generation: '${GEN_BINARY_SCHEMA}'")
register_generated_output(${GEN_BINARY_SCHEMA})
endfunction()
function(compile_flatbuffers_schema_to_embedded_binary SRC_FBS OPT)
if(FLATBUFFERS_BUILD_LEGACY)
set(OPT ${OPT};--cpp-std c++0x)
else()
# --cpp-std is defined by flatc default settings.
endif()
message(STATUS "`${SRC_FBS}`: add generation of C++ embedded binary schema code with '${OPT}'")
get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH)
string(REGEX REPLACE "\\.fbs$" "_bfbs_generated.h" GEN_BFBS_HEADER ${SRC_FBS})
# For details about flags see generate_code.py
add_custom_command(
OUTPUT ${GEN_BFBS_HEADER}
COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}"
--cpp --gen-mutable --gen-object-api --reflect-names
--cpp-ptr-type flatbuffers::unique_ptr # Used to test with C++98 STLs
${OPT}
--bfbs-comments --bfbs-builtins --bfbs-gen-embed
--bfbs-filenames ${SRC_FBS_DIR}
-I "${CMAKE_CURRENT_SOURCE_DIR}/tests/include_test"
-o "${SRC_FBS_DIR}"
"${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}"
DEPENDS flatc
COMMENT "Run generation: '${GEN_BFBS_HEADER}'")
register_generated_output(${GEN_BFBS_HEADER})
function(compile_schema_for_samples SRC_FBS OPT)
compile_schema("${SRC_FBS}" "${OPT}" GEN_FILE)
target_sources(flatsample PRIVATE ${GEN_FILE})
endfunction()
if(FLATBUFFERS_BUILD_TESTS)
file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/tests" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}")
file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/samples" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}")
# TODO Add (monster_test.fbs monsterdata_test.json)->monsterdata_test.mon
compile_flatbuffers_schema_to_cpp(tests/monster_test.fbs)
compile_flatbuffers_schema_to_binary(tests/monster_test.fbs)
compile_flatbuffers_schema_to_cpp_opt(tests/namespace_test/namespace_test1.fbs "--no-includes;--gen-compare;--gen-name-strings")
compile_flatbuffers_schema_to_cpp_opt(tests/namespace_test/namespace_test2.fbs "--no-includes;--gen-compare;--gen-name-strings")
compile_flatbuffers_schema_to_cpp_opt(tests/union_vector/union_vector.fbs "--no-includes;--gen-compare;")
compile_flatbuffers_schema_to_cpp(tests/optional_scalars.fbs)
compile_flatbuffers_schema_to_cpp_opt(tests/native_type_test.fbs "")
compile_flatbuffers_schema_to_cpp_opt(tests/arrays_test.fbs "--scoped-enums;--gen-compare")
compile_flatbuffers_schema_to_binary(tests/arrays_test.fbs)
compile_flatbuffers_schema_to_embedded_binary(tests/monster_test.fbs "--no-includes;--gen-compare")
compile_flatbuffers_schema_to_cpp(tests/native_inline_table_test.fbs "--gen-compare")
compile_flatbuffers_schema_to_cpp(tests/alignment_test.fbs "--gen-compare")
compile_flatbuffers_schema_to_cpp(tests/key_field/key_field_sample.fbs)
if(NOT (MSVC AND (MSVC_VERSION LESS 1900)))
compile_flatbuffers_schema_to_cpp(tests/monster_extra.fbs) # Test floating-point NAN/INF.
endif()
include_directories(${CMAKE_CURRENT_BINARY_DIR}/tests)
add_executable(flattests ${FlatBuffers_Tests_SRCS})
target_link_libraries(flattests PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
target_include_directories(flattests PUBLIC
# Ideally everything is fully qualified from the root directories
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_CURRENT_BINARY_DIR}
# TODO(derekbailey): update includes to fully qualify src/ and tests/
src
tests
${CMAKE_CURRENT_BINARY_DIR}/tests
)
add_dependencies(flattests generated_code)
# Have tests load data from the source directory, not the build directory.
add_definitions(-DFLATBUFFERS_TEST_PATH_PREFIX=${CMAKE_CURRENT_SOURCE_DIR}/)
# The flattest target needs some generated files
SET(FLATC_OPT --cpp --gen-mutable --gen-object-api --reflect-names)
SET(FLATC_OPT_COMP ${FLATC_OPT};--gen-compare)
compile_schema_for_test(tests/alignment_test.fbs "${FLATC_OPT_COMP}")
compile_schema_for_test(tests/arrays_test.fbs "${FLATC_OPT_COMP};--scoped-enums")
compile_schema_for_test(tests/native_inline_table_test.fbs "${FLATC_OPT_COMP}")
compile_schema_for_test(tests/native_type_test.fbs "${FLATC_OPT}")
compile_schema_for_test(tests/key_field/key_field_sample.fbs "${FLATC_OPT_COMP}")
compile_schema_for_test(tests/64bit/test_64bit.fbs "${FLATC_OPT_COMP};--bfbs-gen-embed")
compile_schema_for_test(tests/64bit/evolution/v1.fbs "${FLATC_OPT_COMP}")
compile_schema_for_test(tests/64bit/evolution/v2.fbs "${FLATC_OPT_COMP}")
compile_schema_for_test(tests/union_underlying_type_test.fbs "${FLATC_OPT_COMP}")
if(FLATBUFFERS_CODE_SANITIZE)
add_fsanitize_to_target(flattests ${FLATBUFFERS_CODE_SANITIZE})
endif()
compile_flatbuffers_schema_to_cpp(samples/monster.fbs)
compile_flatbuffers_schema_to_binary(samples/monster.fbs)
include_directories(${CMAKE_CURRENT_BINARY_DIR}/samples)
add_executable(flatsamplebinary ${FlatBuffers_Sample_Binary_SRCS})
target_link_libraries(flatsamplebinary PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
add_dependencies(flatsamplebinary generated_code)
add_executable(flatsampletext ${FlatBuffers_Sample_Text_SRCS})
target_link_libraries(flatsampletext PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
add_dependencies(flatsampletext generated_code)
add_executable(flatsamplebfbs ${FlatBuffers_Sample_BFBS_SRCS})
target_link_libraries(flatsamplebfbs PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
add_dependencies(flatsamplebfbs generated_code)
# Add a library so there is a single target that the generated samples can
# link too.
add_library(flatsample INTERFACE)
# Since flatsample has no sources, we have to explicitly set the linker lang.
set_target_properties(flatsample PROPERTIES LINKER_LANGUAGE CXX)
compile_schema_for_samples(samples/monster.fbs "${FLATC_OPT_COMP}")
target_link_libraries(flatsamplebinary PRIVATE $<BUILD_INTERFACE:ProjectConfig> flatsample)
target_link_libraries(flatsampletext PRIVATE $<BUILD_INTERFACE:ProjectConfig> flatsample)
target_link_libraries(flatsamplebfbs PRIVATE $<BUILD_INTERFACE:ProjectConfig> flatsample)
if(FLATBUFFERS_BUILD_CPP17)
# Don't generate header for flattests_cpp17 target.
# This target uses "generated_cpp17/monster_test_generated.h"
add_executable(flattests_cpp17 ${FlatBuffers_Tests_CPP17_SRCS})
add_dependencies(flattests_cpp17 generated_code)
target_link_libraries(flattests_cpp17 PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
target_compile_features(flattests_cpp17 PRIVATE cxx_std_17)
target_include_directories(flattests_cpp17 PUBLIC src tests)
target_compile_features(flattests_cpp17 PRIVATE cxx_std_17) # requires cmake 3.8
if(FLATBUFFERS_CODE_SANITIZE)
add_fsanitize_to_target(flattests_cpp17 ${FLATBUFFERS_CODE_SANITIZE})
@@ -699,7 +592,6 @@ if(FLATBUFFERS_BUILD_GRPCTEST)
find_package(protobuf CONFIG REQUIRED)
find_package(gRPC CONFIG REQUIRED)
add_executable(grpctest ${FlatBuffers_GRPCTest_SRCS})
add_dependencies(grpctest generated_code)
target_link_libraries(grpctext
PRIVATE
$<BUILD_INTERFACE:ProjectConfig>
@@ -792,16 +684,6 @@ if(FLATBUFFERS_BUILD_TESTS)
endif()
endif()
# This target is sync-barrier.
# Other generate-dependent targets can depend on 'generated_code' only.
get_generated_output(fbs_generated)
if(fbs_generated)
# message(STATUS "Add generated_code target with files:${fbs_generated}")
add_custom_target(generated_code
DEPENDS ${fbs_generated}
COMMENT "All generated files were updated.")
endif()
include(CMake/BuildFlatBuffers.cmake)
if(UNIX)

View File

@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'FlatBuffers'
s.version = '23.1.21'
s.version = '23.5.26'
s.summary = 'FlatBuffers: Memory Efficient Serialization Library'
s.description = "FlatBuffers is a cross platform serialization library architected for

View File

@@ -14,14 +14,55 @@
**FlatBuffers** is a cross platform serialization library architected for
maximum memory efficiency. It allows you to directly access serialized data without parsing/unpacking it first, while still having great forwards/backwards compatibility.
## Quick Start
1. Build the compiler for flatbuffers (`flatc`)
Use `cmake` to create the build files for your platform and then perform the compliation (Linux example).
```
cmake -G "Unix Makefiles"
make -j
```
2. Define your flatbuffer schema (`.fbs`)
Write the [schema](https://flatbuffers.dev/flatbuffers_guide_writing_schema.html) to define the data you want to serialize. See [monster.fbs](https://github.com/google/flatbuffers/blob/master/samples/monster.fbs) for an example.
3. Generate code for your language(s)
Use the `flatc` compiler to take your schema and generate language-specific code:
```
./flatc --cpp --rust monster.fbs
```
Which generates `monster_generated.h` and `monster_generated.rs` files.
4. Serialize data
Use the generated code, as well as the `FlatBufferBuilder` to construct your serialized buffer. ([`C++` example](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.cpp#L24-L56))
5. Transmit/store/save Buffer
Use your serialized buffer however you want. Send it to someone, save it for later, etc...
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/schema version, FlatBuffers ensures the data is readable across languages and schema versions. See the [`Rust` example](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.rs#L92-L106) reading the data written by `C++`.
## Documentation
**Go to our [landing page][] to browse our documentation.**
## Supported operating systems
* Windows
* macOS
* Linux
* Android
* And any others with a recent C++ compiler (C++ 11 and newer)
- Windows
- macOS
- Linux
- Android
- And any others with a recent C++ compiler (C++ 11 and newer)
## Supported programming languages
@@ -31,14 +72,14 @@ Code generation and runtime libraries for many popular languages.
1. C++ - [snapcraft.io](https://snapcraft.io/flatbuffers)
1. C# - [nuget.org](https://www.nuget.org/packages/Google.FlatBuffers)
1. Dart - [pub.dev](https://pub.dev/packages/flat_buffers)
1. Go - [go.dev](https://pkg.go.dev/github.com/google/flatbuffers/go)
1. Go - [go.dev](https://pkg.go.dev/github.com/google/flatbuffers)
1. Java - [Maven](https://search.maven.org/artifact/com.google.flatbuffers/flatbuffers-java)
1. JavaScript - [NPM](https://www.npmjs.com/package/flatbuffers)
1. Kotlin
1. Lobster
1. Lua
1. PHP
1. Python - [PyPi](https://pypi.org/project/flatbuffers/)
1. Python - [PyPI](https://pypi.org/project/flatbuffers/)
1. Rust - [crates.io](https://crates.io/crates/flatbuffers)
1. Swift - [swiftpackageindex](https://swiftpackageindex.com/google/flatbuffers)
1. TypeScript - [NPM](https://www.npmjs.com/package/flatbuffers)
@@ -46,7 +87,7 @@ Code generation and runtime libraries for many popular languages.
## Versioning
FlatBuffers does not follow traditional Semver versioning (see [rationale](https://github.com/google/flatbuffers/wiki/Versioning)) but rather uses a format of the date of the release.
FlatBuffers does not follow traditional SemVer versioning (see [rationale](https://github.com/google/flatbuffers/wiki/Versioning)) but rather uses a format of the date of the release.
## Contribution
@@ -77,4 +118,4 @@ Please see our [Security Policy](SECURITY.md) for reporting vulnerabilities.
[FlatBuffers Issues Tracker]: http://github.com/google/flatbuffers/issues
[stackoverflow.com]: http://stackoverflow.com/search?q=flatbuffers
[landing page]: https://google.github.io/flatbuffers
[LICENSE]: https://github.com/google/flatbuffers/blob/master/LICENSE.txt
[LICENSE]: https://github.com/google/flatbuffers/blob/master/LICENSE

View File

@@ -1,6 +1,6 @@
workspace(name = "com_github_google_flatbuffers")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive", "http_file")
http_archive(
name = "platforms",
@@ -76,30 +76,81 @@ 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 = "build_bazel_rules_nodejs",
sha256 = "965ee2492a2b087cf9e0f2ca472aeaf1be2eb650e0cfbddf514b9a7d3ea4b02a",
urls = ["https://github.com/bazelbuild/rules_nodejs/releases/download/5.2.0/rules_nodejs-5.2.0.tar.gz"],
name = "aspect_rules_js",
sha256 = "124ed29fb0b3d0cba5b44f8f8e07897cf61b34e35e33b1f83d1a943dfd91b193",
strip_prefix = "rules_js-1.24.0",
url = "https://github.com/aspect-build/rules_js/releases/download/v1.24.0/rules_js-v1.24.0.tar.gz",
)
load("@build_bazel_rules_nodejs//:repositories.bzl", "build_bazel_rules_nodejs_dependencies")
load("@aspect_rules_js//js:repositories.bzl", "rules_js_dependencies")
build_bazel_rules_nodejs_dependencies()
rules_js_dependencies()
load("@build_bazel_rules_nodejs//:index.bzl", "node_repositories", "yarn_install")
load("@aspect_rules_js//npm:npm_import.bzl", "npm_translate_lock", "pnpm_repository")
node_repositories()
pnpm_repository(name = "pnpm")
yarn_install(
http_archive(
name = "aspect_rules_ts",
sha256 = "8eb25d1fdafc0836f5778d33fb8eaac37c64176481d67872b54b0a05de5be5c0",
strip_prefix = "rules_ts-1.3.3",
url = "https://github.com/aspect-build/rules_ts/releases/download/v1.3.3/rules_ts-v1.3.3.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.0.4 | jq ._integrity
ts_integrity = "sha512-cW9T5W9xY37cc+jfEnaUvX91foxtHkza3Nw3wkoF4sSlKn0MONdkdEndig/qPBWXNkmplh3NzayQzCiHM4/hqw==",
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",
exports_directories_only = False,
# Unfreeze to add/remove packages.
frozen_lockfile = False,
package_json = "//:package.json",
symlink_node_modules = False,
yarn_lock = "//:yarn.lock",
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("@build_bazel_rules_nodejs//toolchains/esbuild:esbuild_repositories.bzl", "esbuild_repositories")
load("@npm//:repositories.bzl", "npm_repositories")
esbuild_repositories(npm_repository = "npm")
npm_repositories()
http_archive(
name = "aspect_rules_esbuild",
sha256 = "2ea31bd97181a315e048be693ddc2815fddda0f3a12ca7b7cc6e91e80f31bac7",
strip_prefix = "rules_esbuild-0.14.4",
url = "https://github.com/aspect-build/rules_esbuild/releases/download/v0.14.4/rules_esbuild-v0.14.4.tar.gz",
)
# Register a toolchain containing esbuild npm package and native bindings
load("@aspect_rules_esbuild//esbuild:repositories.bzl", "LATEST_VERSION", "esbuild_register_toolchains")
esbuild_register_toolchains(
name = "esbuild",
esbuild_version = LATEST_VERSION,
)
http_file(
name = "bazel_linux_x86_64",
downloaded_file_path = "bazel",
executable = True,
sha256 = "e89747d63443e225b140d7d37ded952dacea73aaed896bca01ccd745827c6289",
urls = [
"https://github.com/bazelbuild/bazel/releases/download/6.1.2/bazel-6.1.2-linux-x86_64",
],
)

View File

@@ -1,20 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- Copyright (c) 2014 Google, Inc.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
-->
<projectDescription>
<name>FlatBufferTest</name>
<name>FlatBufferTest</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
</buildSpec>
<natures>
</natures>
<filteredResources>
<filter>
<id>1677235311958</id>
<name></name>
<type>30</type>
<matcher>
<id>org.eclipse.core.resources.regexFilterMatcher</id>
<arguments>node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__</arguments>
</matcher>
</filter>
</filteredResources>
</projectDescription>

View File

@@ -1,15 +1,13 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 30
buildToolsVersion "30.0.2"
compileSdk 33
defaultConfig {
applicationId "com.flatbuffers.app"
minSdkVersion 26
targetSdkVersion 30
targetSdkVersion 33
versionCode 1
versionName "1.0"
@@ -113,13 +111,13 @@ android {
dependsOn(generateFbsCpp)
}
}
namespace 'com.flatbuffers.app'
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.appcompat:appcompat:1.6.1'
// If you using java runtime you can add its dependency as the example below
// implementation 'com.google.flatbuffers:flatbuffers-java:$latest_version'

View File

@@ -1,6 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.flatbuffers.app">
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:allowBackup="true"
@@ -9,7 +8,8 @@
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<activity android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

View File

@@ -48,7 +48,6 @@ find_library( # Sets the name of the path variable.
target_link_libraries( # Specifies the target library.
native-lib
flatbuffers
flatbuffers_tests
# Links the target library to the log library
# included in the NDK.
${log-lib} )

View File

@@ -18,7 +18,6 @@ set(FlatBuffers_Library_SRCS
${FLATBUFFERS_SRC}/include/flatbuffers/allocator.h
${FLATBUFFERS_SRC}/include/flatbuffers/array.h
${FLATBUFFERS_SRC}/include/flatbuffers/base.h
${FLATBUFFERS_SRC}/include/flatbuffers/bfbs_generator.h
${FLATBUFFERS_SRC}/include/flatbuffers/buffer.h
${FLATBUFFERS_SRC}/include/flatbuffers/buffer_ref.h
${FLATBUFFERS_SRC}/include/flatbuffers/default_allocator.h
@@ -49,26 +48,9 @@ set(FlatBuffers_Library_SRCS
${FLATBUFFERS_SRC}/src/code_generators.cpp
)
set(FlatBuffers_Test_SRCS
${FLATBUFFERS_SRC}/tests/test.cpp
${FLATBUFFERS_SRC}/tests/test_assert.h
${FLATBUFFERS_SRC}/tests/test_builder.h
${FLATBUFFERS_SRC}/tests/test_assert.cpp
${FLATBUFFERS_SRC}/tests/test_builder.cpp
${FLATBUFFERS_SRC}/tests/native_type_test_impl.h
${FLATBUFFERS_SRC}/tests/native_type_test_impl.cpp
)
add_library( # Sets the name of the library.
flatbuffers
${FlatBuffers_Library_SRCS}
${FlatBuffers_Test_SRCS}
${Generated_SRCS}
)
add_library( # Sets the name of the library.
flatbuffers_tests
${FlatBuffers_Test_SRCS}
)

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 == 8,
static_assert(FLATBUFFERS_VERSION_MAJOR == 23 &&
FLATBUFFERS_VERSION_MINOR == 1 &&
FLATBUFFERS_VERSION_REVISION == 21,
"Non-compatible flatbuffers version included");
namespace com {
@@ -20,23 +20,23 @@ namespace app {
struct Animal;
struct AnimalBuilder;
struct Animal FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
struct Animal FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table {
typedef AnimalBuilder Builder;
enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
VT_NAME = 4,
VT_SOUND = 6,
VT_WEIGHT = 8
};
const flatbuffers::String *name() const {
return GetPointer<const flatbuffers::String *>(VT_NAME);
const ::flatbuffers::String *name() const {
return GetPointer<const ::flatbuffers::String *>(VT_NAME);
}
const flatbuffers::String *sound() const {
return GetPointer<const flatbuffers::String *>(VT_SOUND);
const ::flatbuffers::String *sound() const {
return GetPointer<const ::flatbuffers::String *>(VT_SOUND);
}
uint16_t weight() const {
return GetField<uint16_t>(VT_WEIGHT, 0);
}
bool Verify(flatbuffers::Verifier &verifier) const {
bool Verify(::flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyOffset(verifier, VT_NAME) &&
verifier.VerifyString(name()) &&
@@ -49,32 +49,32 @@ struct Animal FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
struct AnimalBuilder {
typedef Animal Table;
flatbuffers::FlatBufferBuilder &fbb_;
flatbuffers::uoffset_t start_;
void add_name(flatbuffers::Offset<flatbuffers::String> name) {
::flatbuffers::FlatBufferBuilder &fbb_;
::flatbuffers::uoffset_t start_;
void add_name(::flatbuffers::Offset<::flatbuffers::String> name) {
fbb_.AddOffset(Animal::VT_NAME, name);
}
void add_sound(flatbuffers::Offset<flatbuffers::String> sound) {
void add_sound(::flatbuffers::Offset<::flatbuffers::String> sound) {
fbb_.AddOffset(Animal::VT_SOUND, sound);
}
void add_weight(uint16_t weight) {
fbb_.AddElement<uint16_t>(Animal::VT_WEIGHT, weight, 0);
}
explicit AnimalBuilder(flatbuffers::FlatBufferBuilder &_fbb)
explicit AnimalBuilder(::flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
}
flatbuffers::Offset<Animal> Finish() {
::flatbuffers::Offset<Animal> Finish() {
const auto end = fbb_.EndTable(start_);
auto o = flatbuffers::Offset<Animal>(end);
auto o = ::flatbuffers::Offset<Animal>(end);
return o;
}
};
inline flatbuffers::Offset<Animal> CreateAnimal(
flatbuffers::FlatBufferBuilder &_fbb,
flatbuffers::Offset<flatbuffers::String> name = 0,
flatbuffers::Offset<flatbuffers::String> sound = 0,
inline ::flatbuffers::Offset<Animal> CreateAnimal(
::flatbuffers::FlatBufferBuilder &_fbb,
::flatbuffers::Offset<::flatbuffers::String> name = 0,
::flatbuffers::Offset<::flatbuffers::String> sound = 0,
uint16_t weight = 0) {
AnimalBuilder builder_(_fbb);
builder_.add_sound(sound);
@@ -83,8 +83,8 @@ inline flatbuffers::Offset<Animal> CreateAnimal(
return builder_.Finish();
}
inline flatbuffers::Offset<Animal> CreateAnimalDirect(
flatbuffers::FlatBufferBuilder &_fbb,
inline ::flatbuffers::Offset<Animal> CreateAnimalDirect(
::flatbuffers::FlatBufferBuilder &_fbb,
const char *name = nullptr,
const char *sound = nullptr,
uint16_t weight = 0) {
@@ -98,32 +98,32 @@ inline flatbuffers::Offset<Animal> CreateAnimalDirect(
}
inline const com::fbs::app::Animal *GetAnimal(const void *buf) {
return flatbuffers::GetRoot<com::fbs::app::Animal>(buf);
return ::flatbuffers::GetRoot<com::fbs::app::Animal>(buf);
}
inline const com::fbs::app::Animal *GetSizePrefixedAnimal(const void *buf) {
return flatbuffers::GetSizePrefixedRoot<com::fbs::app::Animal>(buf);
return ::flatbuffers::GetSizePrefixedRoot<com::fbs::app::Animal>(buf);
}
inline bool VerifyAnimalBuffer(
flatbuffers::Verifier &verifier) {
::flatbuffers::Verifier &verifier) {
return verifier.VerifyBuffer<com::fbs::app::Animal>(nullptr);
}
inline bool VerifySizePrefixedAnimalBuffer(
flatbuffers::Verifier &verifier) {
::flatbuffers::Verifier &verifier) {
return verifier.VerifySizePrefixedBuffer<com::fbs::app::Animal>(nullptr);
}
inline void FinishAnimalBuffer(
flatbuffers::FlatBufferBuilder &fbb,
flatbuffers::Offset<com::fbs::app::Animal> root) {
::flatbuffers::FlatBufferBuilder &fbb,
::flatbuffers::Offset<com::fbs::app::Animal> root) {
fbb.Finish(root);
}
inline void FinishSizePrefixedAnimalBuffer(
flatbuffers::FlatBufferBuilder &fbb,
flatbuffers::Offset<com::fbs::app::Animal> root) {
::flatbuffers::FlatBufferBuilder &fbb,
::flatbuffers::Offset<com::fbs::app::Animal> root) {
fbb.FinishSizePrefixed(root);
}

View File

@@ -19,6 +19,7 @@ import java.nio.ByteOrder
import kotlin.math.sign
@Suppress("unused")
@kotlin.ExperimentalUnsignedTypes
class Animal : Table() {
fun __init(_i: Int, _bb: ByteBuffer) {
@@ -31,14 +32,22 @@ class Animal : Table() {
val name : String?
get() {
val o = __offset(4)
return if (o != 0) __string(o + bb_pos) else null
return if (o != 0) {
__string(o + bb_pos)
} else {
null
}
}
val nameAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(4, 1)
fun nameInByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 4, 1)
val sound : String?
get() {
val o = __offset(6)
return if (o != 0) __string(o + bb_pos) else null
return if (o != 0) {
__string(o + bb_pos)
} else {
null
}
}
val soundAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(6, 1)
fun soundInByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 6, 1)
@@ -48,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_1_21()
fun validateVersion() = Constants.FLATBUFFERS_23_5_26()
fun getRootAsAnimal(_bb: ByteBuffer): Animal = getRootAsAnimal(_bb, Animal())
fun getRootAsAnimal(_bb: ByteBuffer, obj: Animal): Animal {
_bb.order(ByteOrder.LITTLE_ENDIAN)

View File

@@ -1,12 +1,12 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = "1.4.10"
ext.kotlin_version = "1.7.21"
repositories {
google()
jcenter()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.1.0'
classpath 'com.android.tools.build:gradle:7.4.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
@@ -17,7 +17,7 @@ buildscript {
allprojects {
repositories {
google()
jcenter()
mavenCentral()
}
}

View File

@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@@ -1,8 +1,9 @@
# Setup for running Google Benchmarks (https://github.com/google/benchmark) on
# flatbuffers. This requires both that benchmark library and its depenency gtest
# flatbuffers. This requires both that benchmark library and its dependency gtest
# to build. Instead of including them here or doing a submodule, this uses
# FetchContent (https://cmake.org/cmake/help/latest/module/FetchContent.html) to
# grab the dependencies at config time. This requires CMake 3.14 or higher.
cmake_minimum_required(VERSION 3.14)
include(FetchContent)
@@ -62,8 +63,8 @@ add_custom_command(
add_executable(flatbenchmark ${FlatBenchmark_SRCS})
# Benchmark requires C++11
target_compile_features(flatbenchmark PUBLIC
cxx_std_11
target_compile_features(flatbenchmark PRIVATE
cxx_std_11 # requires cmake 3.8
)
target_compile_options(flatbenchmark
@@ -81,7 +82,7 @@ set_target_properties(flatbenchmark
# The includes of the benchmark files are fully qualified from flatbuffers root.
target_include_directories(flatbenchmark PUBLIC ${CMAKE_SOURCE_DIR})
target_link_libraries(flatbenchmark
target_link_libraries(flatbenchmark PRIVATE
benchmark::benchmark_main # _main to use their entry point
gtest # Link to gtest so we can also assert in the benchmarks
)

View File

@@ -48,7 +48,10 @@ def flatbuffer_library_public(
restricted_to = None,
target_compatible_with = None,
flatc_path = "@com_github_google_flatbuffers//:flatc",
output_to_bindir = False):
output_to_bindir = False,
tools = None,
extra_env = None,
**kwargs):
"""Generates code files for reading/writing the given flatbuffers in the requested language using the public compiler.
Args:
@@ -73,6 +76,11 @@ def flatbuffer_library_public(
to use.
flatc_path: Bazel target corresponding to the flatc compiler to use.
output_to_bindir: Passed to genrule for output to bin directory.
tools: Optional, passed to genrule for list of tools to make available
during the action.
extra_env: Optional, must be a string of "VAR1=VAL1 VAR2=VAL2". These get
set as environment variables that "flatc_path" sees.
**kwargs: Passed to the underlying genrule.
This rule creates a filegroup(name) with all generated source files, and
@@ -83,6 +91,8 @@ def flatbuffer_library_public(
include_paths = default_include_paths(flatc_path)
include_paths_cmd = ["-I %s" % (s) for s in include_paths]
extra_env = extra_env or ""
# '$(@D)' when given a single source target will give the appropriate
# directory. Appending 'out_prefix' is only necessary when given a build
# target with multiple sources.
@@ -92,7 +102,7 @@ def flatbuffer_library_public(
genrule_cmd = " ".join([
"SRCS=($(SRCS));",
"for f in $${SRCS[@]:0:%s}; do" % len(srcs),
"OUTPUT_FILE=\"$(OUTS)\" $(location %s)" % (flatc_path),
"OUTPUT_FILE=\"$(OUTS)\" %s $(location %s)" % (extra_env, flatc_path),
" ".join(include_paths_cmd),
" ".join(flatc_args),
language_flag,
@@ -105,12 +115,13 @@ def flatbuffer_library_public(
srcs = srcs + includes,
outs = outs,
output_to_bindir = output_to_bindir,
tools = [flatc_path],
tools = (tools or []) + [flatc_path],
cmd = genrule_cmd,
compatible_with = compatible_with,
target_compatible_with = target_compatible_with,
restricted_to = restricted_to,
message = "Generating flatbuffer files for %s:" % (name),
**kwargs
)
if reflection_name:
reflection_genrule_cmd = " ".join([
@@ -154,6 +165,7 @@ def flatbuffer_cc_library(
name,
srcs,
srcs_filegroup_name = "",
outs = [],
out_prefix = "",
deps = [],
includes = [],
@@ -174,6 +186,7 @@ def flatbuffer_cc_library(
srcs_filegroup_name: Name of the output filegroup that holds srcs. Pass this
filegroup into the `includes` parameter of any other
flatbuffer_cc_library that depends on this one's schemas.
outs: Additional outputs expected to be generated by flatc.
out_prefix: Prepend this path to the front of all generated files. Usually
is a directory name.
deps: Optional, list of other flatbuffer_cc_library's to depend on. Cannot be specified
@@ -221,7 +234,7 @@ def flatbuffer_cc_library(
flatbuffer_library_public(
name = srcs_lib,
srcs = srcs,
outs = output_headers,
outs = outs + output_headers,
language_flag = "-c",
out_prefix = out_prefix,
includes = includes,

View File

@@ -20,7 +20,7 @@ class FlatbuffersConan(ConanFile):
options = {"shared": [True, False], "fPIC": [True, False]}
default_options = {"shared": False, "fPIC": True}
generators = "cmake"
exports = "LICENSE.txt"
exports = "LICENSE"
exports_sources = ["CMake/*", "include/*", "src/*", "grpc/*", "CMakeLists.txt", "conan/CMakeLists.txt"]
def source(self):
@@ -56,7 +56,7 @@ class FlatbuffersConan(ConanFile):
"""
cmake = self.configure_cmake()
cmake.install()
self.copy(pattern="LICENSE.txt", dst="licenses")
self.copy(pattern="LICENSE", dst="licenses")
self.copy(pattern="FindFlatBuffers.cmake", dst=os.path.join("lib", "cmake", "flatbuffers"), src="CMake")
self.copy(pattern="flathash*", dst="bin", src="bin")
self.copy(pattern="flatc*", dst="bin", src="bin")

View File

@@ -304,7 +304,7 @@ class Builder {
assert(_inVTable);
// Prepare for writing the VTable.
_prepare(_sizeofInt32, 1);
var tableTail = _tail;
final tableTail = _tail;
// Prepare the size of the current table.
final currentVTable = _currentVTable!;
currentVTable.tableSize = tableTail - _currentTableEndTail;
@@ -514,7 +514,7 @@ class Builder {
var tail = _tail;
_setUint32AtTail(tail, values.length);
tail -= _sizeofUint32;
for (var value in values) {
for (final value in values) {
_setUint32AtTail(tail, tail - value);
tail -= _sizeofUint32;
}
@@ -529,7 +529,7 @@ class Builder {
var tail = _tail;
_setUint32AtTail(tail, values.length);
tail -= _sizeofUint32;
for (var value in values) {
for (final value in values) {
_setFloat64AtTail(tail, value);
tail -= _sizeofFloat64;
}
@@ -544,7 +544,7 @@ class Builder {
var tail = _tail;
_setUint32AtTail(tail, values.length);
tail -= _sizeofUint32;
for (var value in values) {
for (final value in values) {
_setFloat32AtTail(tail, value);
tail -= _sizeofFloat32;
}
@@ -559,7 +559,7 @@ class Builder {
var tail = _tail;
_setUint32AtTail(tail, values.length);
tail -= _sizeofUint32;
for (var value in values) {
for (final value in values) {
_setInt64AtTail(tail, value);
tail -= _sizeofInt64;
}
@@ -574,7 +574,7 @@ class Builder {
var tail = _tail;
_setUint32AtTail(tail, values.length);
tail -= _sizeofUint32;
for (var value in values) {
for (final value in values) {
_setUint64AtTail(tail, value);
tail -= _sizeofUint64;
}
@@ -589,7 +589,7 @@ class Builder {
var tail = _tail;
_setUint32AtTail(tail, values.length);
tail -= _sizeofUint32;
for (var value in values) {
for (final value in values) {
_setInt32AtTail(tail, value);
tail -= _sizeofInt32;
}
@@ -604,7 +604,7 @@ class Builder {
var tail = _tail;
_setUint32AtTail(tail, values.length);
tail -= _sizeofUint32;
for (var value in values) {
for (final value in values) {
_setUint32AtTail(tail, value);
tail -= _sizeofUint32;
}
@@ -619,7 +619,7 @@ class Builder {
var tail = _tail;
_setUint32AtTail(tail, values.length);
tail -= _sizeofUint32;
for (var value in values) {
for (final value in values) {
_setInt16AtTail(tail, value);
tail -= _sizeofInt16;
}
@@ -634,7 +634,7 @@ class Builder {
var tail = _tail;
_setUint32AtTail(tail, values.length);
tail -= _sizeofUint32;
for (var value in values) {
for (final value in values) {
_setUint16AtTail(tail, value);
tail -= _sizeofUint16;
}
@@ -654,7 +654,7 @@ class Builder {
var tail = _tail;
_setUint32AtTail(tail, values.length);
tail -= _sizeofUint32;
for (var value in values) {
for (final value in values) {
_setInt8AtTail(tail, value);
tail -= _sizeofUint8;
}
@@ -669,7 +669,7 @@ class Builder {
var tail = _tail;
_setUint32AtTail(tail, values.length);
tail -= _sizeofUint32;
for (var value in values) {
for (final value in values) {
_setUint8AtTail(tail, value);
tail -= _sizeofUint8;
}
@@ -777,17 +777,17 @@ class Builder {
_maxAlign = size;
}
// Prepare amount of required space.
var dataSize = size * count + additionalBytes;
var alignDelta = (-(_tail + dataSize)) & (size - 1);
var bufSize = alignDelta + dataSize;
final dataSize = size * count + additionalBytes;
final alignDelta = (-(_tail + dataSize)) & (size - 1);
final bufSize = alignDelta + dataSize;
// Ensure that we have the required amount of space.
{
var oldCapacity = _buf.lengthInBytes;
final oldCapacity = _buf.lengthInBytes;
if (_tail + bufSize > oldCapacity) {
var desiredNewCapacity = (oldCapacity + bufSize) * 2;
final desiredNewCapacity = (oldCapacity + bufSize) * 2;
var deltaCapacity = desiredNewCapacity - oldCapacity;
deltaCapacity += (-deltaCapacity) & (_maxAlign - 1);
var newCapacity = oldCapacity + deltaCapacity;
final newCapacity = oldCapacity + deltaCapacity;
_buf = _allocator.resize(_buf, newCapacity, _tail, 0);
}
}
@@ -1023,22 +1023,22 @@ abstract class Reader<T> {
/// Read the value of the given [field] in the given [object].
@pragma('vm:prefer-inline')
T vTableGet(BufferContext object, int offset, int field, T defaultValue) {
var fieldOffset = _vTableFieldOffset(object, offset, field);
final fieldOffset = _vTableFieldOffset(object, offset, field);
return fieldOffset == 0 ? defaultValue : read(object, offset + fieldOffset);
}
/// Read the value of the given [field] in the given [object].
@pragma('vm:prefer-inline')
T? vTableGetNullable(BufferContext object, int offset, int field) {
var fieldOffset = _vTableFieldOffset(object, offset, field);
final fieldOffset = _vTableFieldOffset(object, offset, field);
return fieldOffset == 0 ? null : read(object, offset + fieldOffset);
}
@pragma('vm:prefer-inline')
int _vTableFieldOffset(BufferContext object, int offset, int field) {
var vTableSOffset = object._getInt32(offset);
var vTableOffset = offset - vTableSOffset;
var vTableSize = object._getUint16(vTableOffset);
final vTableSOffset = object._getInt32(offset);
final vTableOffset = offset - vTableSOffset;
final vTableSize = object._getUint16(vTableOffset);
if (field >= vTableSize) return 0;
return object._getUint16(vTableOffset + field);
}
@@ -1057,9 +1057,9 @@ class StringReader extends Reader<String> {
@override
@pragma('vm:prefer-inline')
String read(BufferContext bc, int offset) {
var strOffset = bc.derefObject(offset);
var length = bc._getUint32(strOffset);
var bytes = bc._asUint8List(strOffset + _sizeofUint32, length);
final strOffset = bc.derefObject(offset);
final length = bc._getUint32(strOffset);
final bytes = bc._asUint8List(strOffset + _sizeofUint32, length);
if (asciiOptimization && _isLatin(bytes)) {
return String.fromCharCodes(bytes);
}
@@ -1068,7 +1068,7 @@ class StringReader extends Reader<String> {
@pragma('vm:prefer-inline')
static bool _isLatin(Uint8List bytes) {
var length = bytes.length;
final length = bytes.length;
for (var i = 0; i < length; i++) {
if (bytes[i] > 127) {
return false;
@@ -1104,7 +1104,7 @@ abstract class TableReader<T> extends Reader<T> {
@override
T read(BufferContext bc, int offset) {
var objectOffset = bc.derefObject(offset);
final objectOffset = bc.derefObject(offset);
return createObject(bc, objectOffset);
}
}

View File

@@ -1,5 +1,5 @@
name: flat_buffers
version: 23.1.21
version: 23.5.26
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

View File

@@ -59,6 +59,8 @@ struct Vec3 (force_align: 8) {
test3:Test;
}
// Stats for monster
struct Ability {
id:uint(key);
distance:uint;

View File

@@ -142,6 +142,47 @@ To use it:
`ByKey` only works if the vector has been sorted, it will
likely not find elements if it hasn't been sorted.
## Buffer verification
As mentioned in [C++ Usage](@ref flatbuffers_guide_use_cpp) 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
fields, and null termination of strings to ensure that when a buffer
is accessed, all reads will end up inside the buffer.
Each root type will have a verification function generated for it,
e.g. `Monster.VerifyMonster`. This can be called as shown:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cs}
var ok = Monster.VerifyMonster(buf);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if `ok` is true, the buffer is safe to read.
For a more detailed control of verification `MonsterVerify.Verify`
for `Monster` type can be used:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cs}
# Sequence of calls
FlatBuffers.Verifier verifier = new FlatBuffers.Verifier(buf);
var ok = verifier.VerifyBuffer("MONS", false, MonsterVerify.Verify);
# Or single line call
var ok = new FlatBuffers.Verifier(bb).setStringCheck(true).\
VerifyBuffer("MONS", false, MonsterVerify.Verify);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if `ok` is true, the buffer is safe to read.
A second parameter of `verifyBuffer` specifies whether buffer content is
size prefixed or not. In the example above, the buffer is assumed to not include
size prefix (`false`).
Verifier supports options that can be set using appropriate fluent methods:
* SetMaxDepth - limit the nesting depth. Default: 1000000
* SetMaxTables - total amount of tables the verifier may encounter. Default: 64
* SetAlignmentCheck - check content alignment. Default: True
* SetStringCheck - check if strings contain termination '0' character. Default: true
## Text parsing
There currently is no support for parsing text (Schema's and JSON) directly

View File

@@ -9,7 +9,7 @@ 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.txt).
under the Apache license, v2 (see LICENSE).
## Why use FlatBuffers?

View File

@@ -529,7 +529,7 @@ The first step is to import/include the library, generated files, etc.
#[allow(dead_code, unused_imports)]
#[path = "./monster_generated.rs"]
mod monster_generated;
pub use monster_generated::my_game::sample::{get_root_as_monster,
pub use monster_generated::my_game::sample::{root_as_monster,
Color, Equipment,
Monster, MonsterArgs,
Vec3,
@@ -652,7 +652,7 @@ which will grow automatically if needed:
~~~{.rs}
// Build up a serialized buffer algorithmically.
// Initialize it with a capacity of 1024 bytes.
let mut builder = flatbuffers::FlatBufferBuilder::new_with_capacity(1024);
let mut builder = flatbuffers::FlatBufferBuilder::with_capacity(1024);
~~~
</div>
<div class="language-swift">
@@ -2309,7 +2309,7 @@ import './monster_my_game.sample_generated.dart' as myGame;
#[allow(dead_code, unused_imports)]
#[path = "./monster_generated.rs"]
mod monster_generated;
pub use monster_generated::my_game::sample::{get_root_as_monster,
pub use monster_generated::my_game::sample::{root_as_monster,
Color, Equipment,
Monster, MonsterArgs,
Vec3,
@@ -2465,7 +2465,7 @@ myGame.Monster monster = new myGame.Monster(data);
let buf = /* the data you just read, in a &[u8] */
// Get an accessor to the root object inside the buffer.
let monster = get_root_as_monster(buf);
let monster = root_as_monster(buf).unwrap();
~~~
</div>
<div class="language-swift">

View File

@@ -779,7 +779,8 @@ INPUT = "FlatBuffers.md" \
"../../python/flatbuffers/builder.py" \
"../../js/flatbuffers.js" \
"../../php/FlatbufferBuilder.php" \
"../../net/FlatBuffers/FlatBufferBuilder.cs" \
"../../net/FlatBuffers/FlatBufferBuilder.cs"
"../../net/FlatBuffers/FlatBufferVerify.cs" \
"../../include/flatbuffers/flatbuffers.h" \
"../../go/builder.go" \
"../../rust/flatbuffers/src/builder.rs"

View File

@@ -12,8 +12,13 @@ type WarriorT struct {
}
func (t *WarriorT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
if t == nil { return 0 }
nameOffset := builder.CreateString(t.Name)
if t == nil {
return 0
}
nameOffset := flatbuffers.UOffsetT(0)
if t.Name != "" {
nameOffset = builder.CreateString(t.Name)
}
WarriorStart(builder)
WarriorAddName(builder, nameOffset)
WarriorAddHp(builder, t.Hp)
@@ -26,7 +31,9 @@ func (rcv *Warrior) UnPackTo(t *WarriorT) {
}
func (rcv *Warrior) UnPack() *WarriorT {
if rcv == nil { return nil }
if rcv == nil {
return nil
}
t := &WarriorT{}
rcv.UnPackTo(t)
return t

View File

@@ -13,7 +13,9 @@ type RequestT struct {
}
func (t *RequestT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
if t == nil { return 0 }
if t == nil {
return 0
}
playerOffset := t.Player.Pack(builder)
RequestStart(builder)
RequestAddPlayer(builder, playerOffset)
@@ -25,7 +27,9 @@ func (rcv *Request) UnPackTo(t *RequestT) {
}
func (rcv *Request) UnPack() *RequestT {
if rcv == nil { return nil }
if rcv == nil {
return nil
}
t := &RequestT{}
rcv.UnPackTo(t)
return t

View File

@@ -13,7 +13,9 @@ type ResponseT struct {
}
func (t *ResponseT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
if t == nil { return 0 }
if t == nil {
return 0
}
playerOffset := t.Player.Pack(builder)
ResponseStart(builder)
ResponseAddPlayer(builder, playerOffset)
@@ -25,7 +27,9 @@ func (rcv *Response) UnPackTo(t *ResponseT) {
}
func (rcv *Response) UnPack() *ResponseT {
if rcv == nil { return nil }
if rcv == nil {
return nil
}
t := &ResponseT{}
rcv.UnPackTo(t)
return t

View File

@@ -28,3 +28,23 @@ func GetSizePrefix(buf []byte, offset UOffsetT) uint32 {
func GetIndirectOffset(buf []byte, offset UOffsetT) UOffsetT {
return offset + GetUOffsetT(buf[offset:])
}
// GetBufferIdentifier returns the file identifier as string
func GetBufferIdentifier(buf []byte) string {
return string(buf[SizeUOffsetT:][:fileIdentifierLength])
}
// GetBufferIdentifier returns the file identifier as string for a size-prefixed buffer
func GetSizePrefixedBufferIdentifier(buf []byte) string {
return string(buf[SizeUOffsetT+sizePrefixLength:][:fileIdentifierLength])
}
// BufferHasIdentifier checks if the identifier in a buffer has the expected value
func BufferHasIdentifier(buf []byte, identifier string) bool {
return GetBufferIdentifier(buf) == identifier
}
// BufferHasIdentifier checks if the identifier in a buffer has the expected value for a size-prefixed buffer
func SizePrefixedBufferHasIdentifier(buf []byte, identifier string) bool {
return GetSizePrefixedBufferIdentifier(buf) == identifier
}

26
goldens/README.md Normal file
View File

@@ -0,0 +1,26 @@
# Golden Generated Files
This directory is a repository for the generated files of `flatc`.
We check in the generated code so we can see, during a PR review, how the
changes affect the generated output. Its also useful as a reference to point too
as how things work across various languages.
These files are **NOT** intended to be depended on by any code, such as tests or
or compiled examples.
## Languages Specifics
Each language should keep their generated code in their respective directories.
However, the parent schemas can, and should, be shared so we have a consistent
view of things across languages. These are kept in the `schema/` directory.
Some languages may not support every generation feature, so each language is
required to specify the `flatc` arguments individually.
* Try to avoid includes and nested directories, preferring it as flat as
possible.
## Updating
Just run the `generate_goldens.py` script and it should generate them all.

View File

@@ -0,0 +1,157 @@
// automatically generated by the FlatBuffers compiler, do not modify
#ifndef FLATBUFFERS_GENERATED_BASIC_H_
#define FLATBUFFERS_GENERATED_BASIC_H_
#include "flatbuffers/flatbuffers.h"
// Ensure the included flatbuffers.h is the same version as when this file was
// generated, otherwise it may not be compatible.
static_assert(FLATBUFFERS_VERSION_MAJOR == 23 &&
FLATBUFFERS_VERSION_MINOR == 5 &&
FLATBUFFERS_VERSION_REVISION == 9,
"Non-compatible flatbuffers version included");
struct Galaxy;
struct GalaxyBuilder;
struct Universe;
struct UniverseBuilder;
struct Galaxy FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table {
typedef GalaxyBuilder Builder;
enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
VT_NUM_STARS = 4
};
int64_t num_stars() const {
return GetField<int64_t>(VT_NUM_STARS, 0);
}
bool Verify(::flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyField<int64_t>(verifier, VT_NUM_STARS, 8) &&
verifier.EndTable();
}
};
struct GalaxyBuilder {
typedef Galaxy Table;
::flatbuffers::FlatBufferBuilder &fbb_;
::flatbuffers::uoffset_t start_;
void add_num_stars(int64_t num_stars) {
fbb_.AddElement<int64_t>(Galaxy::VT_NUM_STARS, num_stars, 0);
}
explicit GalaxyBuilder(::flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
}
::flatbuffers::Offset<Galaxy> Finish() {
const auto end = fbb_.EndTable(start_);
auto o = ::flatbuffers::Offset<Galaxy>(end);
return o;
}
};
inline ::flatbuffers::Offset<Galaxy> CreateGalaxy(
::flatbuffers::FlatBufferBuilder &_fbb,
int64_t num_stars = 0) {
GalaxyBuilder builder_(_fbb);
builder_.add_num_stars(num_stars);
return builder_.Finish();
}
struct Universe FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table {
typedef UniverseBuilder Builder;
enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
VT_AGE = 4,
VT_GALAXIES = 6
};
double age() const {
return GetField<double>(VT_AGE, 0.0);
}
const ::flatbuffers::Vector<::flatbuffers::Offset<Galaxy>> *galaxies() const {
return GetPointer<const ::flatbuffers::Vector<::flatbuffers::Offset<Galaxy>> *>(VT_GALAXIES);
}
bool Verify(::flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyField<double>(verifier, VT_AGE, 8) &&
VerifyOffset(verifier, VT_GALAXIES) &&
verifier.VerifyVector(galaxies()) &&
verifier.VerifyVectorOfTables(galaxies()) &&
verifier.EndTable();
}
};
struct UniverseBuilder {
typedef Universe Table;
::flatbuffers::FlatBufferBuilder &fbb_;
::flatbuffers::uoffset_t start_;
void add_age(double age) {
fbb_.AddElement<double>(Universe::VT_AGE, age, 0.0);
}
void add_galaxies(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<Galaxy>>> galaxies) {
fbb_.AddOffset(Universe::VT_GALAXIES, galaxies);
}
explicit UniverseBuilder(::flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
}
::flatbuffers::Offset<Universe> Finish() {
const auto end = fbb_.EndTable(start_);
auto o = ::flatbuffers::Offset<Universe>(end);
return o;
}
};
inline ::flatbuffers::Offset<Universe> CreateUniverse(
::flatbuffers::FlatBufferBuilder &_fbb,
double age = 0.0,
::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<Galaxy>>> galaxies = 0) {
UniverseBuilder builder_(_fbb);
builder_.add_age(age);
builder_.add_galaxies(galaxies);
return builder_.Finish();
}
inline ::flatbuffers::Offset<Universe> CreateUniverseDirect(
::flatbuffers::FlatBufferBuilder &_fbb,
double age = 0.0,
const std::vector<::flatbuffers::Offset<Galaxy>> *galaxies = nullptr) {
auto galaxies__ = galaxies ? _fbb.CreateVector<::flatbuffers::Offset<Galaxy>>(*galaxies) : 0;
return CreateUniverse(
_fbb,
age,
galaxies__);
}
inline const Universe *GetUniverse(const void *buf) {
return ::flatbuffers::GetRoot<Universe>(buf);
}
inline const Universe *GetSizePrefixedUniverse(const void *buf) {
return ::flatbuffers::GetSizePrefixedRoot<Universe>(buf);
}
inline bool VerifyUniverseBuffer(
::flatbuffers::Verifier &verifier) {
return verifier.VerifyBuffer<Universe>(nullptr);
}
inline bool VerifySizePrefixedUniverseBuffer(
::flatbuffers::Verifier &verifier) {
return verifier.VerifySizePrefixedBuffer<Universe>(nullptr);
}
inline void FinishUniverseBuffer(
::flatbuffers::FlatBufferBuilder &fbb,
::flatbuffers::Offset<Universe> root) {
fbb.Finish(root);
}
inline void FinishSizePrefixedUniverseBuffer(
::flatbuffers::FlatBufferBuilder &fbb,
::flatbuffers::Offset<Universe> root) {
fbb.FinishSizePrefixed(root);
}
#endif // FLATBUFFERS_GENERATED_BASIC_H_

10
goldens/cpp/generate.py Normal file
View File

@@ -0,0 +1,10 @@
from golden_utils import flatc_golden
def flatc(options, schema):
# Wrap the golden flatc generator with C++ specifics
flatc_golden(options=["--cpp"] + options, schema=schema, prefix="cpp")
def GenerateCpp():
flatc([], "basic.fbs")

45
goldens/csharp/Galaxy.cs Normal file
View File

@@ -0,0 +1,45 @@
// <auto-generated>
// automatically generated by the FlatBuffers compiler, do not modify
// </auto-generated>
using global::System;
using global::System.Collections.Generic;
using global::Google.FlatBuffers;
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 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); }
public Galaxy __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
public long NumStars { get { int o = __p.__offset(4); return o != 0 ? __p.bb.GetLong(o + __p.bb_pos) : (long)0; } }
public static Offset<Galaxy> CreateGalaxy(FlatBufferBuilder builder,
long num_stars = 0) {
builder.StartTable(1);
Galaxy.AddNumStars(builder, num_stars);
return Galaxy.EndGalaxy(builder);
}
public static void StartGalaxy(FlatBufferBuilder builder) { builder.StartTable(1); }
public static void AddNumStars(FlatBufferBuilder builder, long numStars) { builder.AddLong(0, numStars, 0); }
public static Offset<Galaxy> EndGalaxy(FlatBufferBuilder builder) {
int o = builder.EndTable();
return new Offset<Galaxy>(o);
}
}
static public class GalaxyVerify
{
static public bool Verify(Google.FlatBuffers.Verifier verifier, uint tablePos)
{
return verifier.VerifyTableStart(tablePos)
&& verifier.VerifyField(tablePos, 4 /*NumStars*/, 8 /*long*/, 8, false)
&& verifier.VerifyTableEnd(tablePos);
}
}

View File

@@ -0,0 +1,59 @@
// <auto-generated>
// automatically generated by the FlatBuffers compiler, do not modify
// </auto-generated>
using global::System;
using global::System.Collections.Generic;
using global::Google.FlatBuffers;
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 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); }
public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); }
public Universe __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
public double Age { get { int o = __p.__offset(4); return o != 0 ? __p.bb.GetDouble(o + __p.bb_pos) : (double)0.0; } }
public Galaxy? Galaxies(int j) { int o = __p.__offset(6); return o != 0 ? (Galaxy?)(new Galaxy()).__assign(__p.__indirect(__p.__vector(o) + j * 4), __p.bb) : null; }
public int GalaxiesLength { get { int o = __p.__offset(6); return o != 0 ? __p.__vector_len(o) : 0; } }
public static Offset<Universe> CreateUniverse(FlatBufferBuilder builder,
double age = 0.0,
VectorOffset galaxiesOffset = default(VectorOffset)) {
builder.StartTable(2);
Universe.AddAge(builder, age);
Universe.AddGalaxies(builder, galaxiesOffset);
return Universe.EndUniverse(builder);
}
public static void StartUniverse(FlatBufferBuilder builder) { builder.StartTable(2); }
public static void AddAge(FlatBufferBuilder builder, double age) { builder.AddDouble(0, age, 0.0); }
public static void AddGalaxies(FlatBufferBuilder builder, VectorOffset galaxiesOffset) { builder.AddOffset(1, galaxiesOffset.Value, 0); }
public static VectorOffset CreateGalaxiesVector(FlatBufferBuilder builder, Offset<Galaxy>[] data) { builder.StartVector(4, data.Length, 4); for (int i = data.Length - 1; i >= 0; i--) builder.AddOffset(data[i].Value); return builder.EndVector(); }
public static VectorOffset CreateGalaxiesVectorBlock(FlatBufferBuilder builder, Offset<Galaxy>[] data) { builder.StartVector(4, data.Length, 4); builder.Add(data); return builder.EndVector(); }
public static VectorOffset CreateGalaxiesVectorBlock(FlatBufferBuilder builder, ArraySegment<Offset<Galaxy>> data) { builder.StartVector(4, data.Count, 4); builder.Add(data); return builder.EndVector(); }
public static VectorOffset CreateGalaxiesVectorBlock(FlatBufferBuilder builder, IntPtr dataPtr, int sizeInBytes) { builder.StartVector(1, sizeInBytes, 1); builder.Add<Offset<Galaxy>>(dataPtr, sizeInBytes); return builder.EndVector(); }
public static void StartGalaxiesVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 4); }
public static Offset<Universe> EndUniverse(FlatBufferBuilder builder) {
int o = builder.EndTable();
return new Offset<Universe>(o);
}
public static void FinishUniverseBuffer(FlatBufferBuilder builder, Offset<Universe> offset) { builder.Finish(offset.Value); }
public static void FinishSizePrefixedUniverseBuffer(FlatBufferBuilder builder, Offset<Universe> offset) { builder.FinishSizePrefixed(offset.Value); }
}
static public class UniverseVerify
{
static public bool Verify(Google.FlatBuffers.Verifier verifier, uint tablePos)
{
return verifier.VerifyTableStart(tablePos)
&& verifier.VerifyField(tablePos, 4 /*Age*/, 8 /*double*/, 8, false)
&& verifier.VerifyVectorOfTables(tablePos, 6 /*Galaxies*/, GalaxyVerify.Verify, false)
&& verifier.VerifyTableEnd(tablePos);
}
}

View File

@@ -0,0 +1,10 @@
from golden_utils import flatc_golden
def flatc(options, schema):
# Wrap the golden flatc generator with C# specifics
flatc_golden(options=["--csharp"] + options, schema=schema, prefix="csharp")
def GenerateCSharp():
flatc([], "basic.fbs")

View File

@@ -0,0 +1,160 @@
// automatically generated by the FlatBuffers compiler, do not modify
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
import 'dart:typed_data' show Uint8List;
import 'package:flat_buffers/flat_buffers.dart' as fb;
class Galaxy {
Galaxy._(this._bc, this._bcOffset);
factory Galaxy(List<int> bytes) {
final rootRef = fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}
static const fb.Reader<Galaxy> reader = _GalaxyReader();
final fb.BufferContext _bc;
final int _bcOffset;
int get numStars => const fb.Int64Reader().vTableGet(_bc, _bcOffset, 4, 0);
@override
String toString() {
return 'Galaxy{numStars: ${numStars}}';
}
}
class _GalaxyReader extends fb.TableReader<Galaxy> {
const _GalaxyReader();
@override
Galaxy createObject(fb.BufferContext bc, int offset) =>
Galaxy._(bc, offset);
}
class GalaxyBuilder {
GalaxyBuilder(this.fbBuilder);
final fb.Builder fbBuilder;
void begin() {
fbBuilder.startTable(1);
}
int addNumStars(int? numStars) {
fbBuilder.addInt64(0, numStars);
return fbBuilder.offset;
}
int finish() {
return fbBuilder.endTable();
}
}
class GalaxyObjectBuilder extends fb.ObjectBuilder {
final int? _numStars;
GalaxyObjectBuilder({
int? numStars,
})
: _numStars = numStars;
/// Finish building, and store into the [fbBuilder].
@override
int finish(fb.Builder fbBuilder) {
fbBuilder.startTable(1);
fbBuilder.addInt64(0, _numStars);
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
Uint8List toBytes([String? fileIdentifier]) {
final fbBuilder = fb.Builder(deduplicateTables: false);
fbBuilder.finish(finish(fbBuilder), fileIdentifier);
return fbBuilder.buffer;
}
}
class Universe {
Universe._(this._bc, this._bcOffset);
factory Universe(List<int> bytes) {
final rootRef = fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}
static const fb.Reader<Universe> reader = _UniverseReader();
final fb.BufferContext _bc;
final int _bcOffset;
double get age => const fb.Float64Reader().vTableGet(_bc, _bcOffset, 4, 0.0);
List<Galaxy>? get galaxies => const fb.ListReader<Galaxy>(Galaxy.reader).vTableGetNullable(_bc, _bcOffset, 6);
@override
String toString() {
return 'Universe{age: ${age}, galaxies: ${galaxies}}';
}
}
class _UniverseReader extends fb.TableReader<Universe> {
const _UniverseReader();
@override
Universe createObject(fb.BufferContext bc, int offset) =>
Universe._(bc, offset);
}
class UniverseBuilder {
UniverseBuilder(this.fbBuilder);
final fb.Builder fbBuilder;
void begin() {
fbBuilder.startTable(2);
}
int addAge(double? age) {
fbBuilder.addFloat64(0, age);
return fbBuilder.offset;
}
int addGalaxiesOffset(int? offset) {
fbBuilder.addOffset(1, offset);
return fbBuilder.offset;
}
int finish() {
return fbBuilder.endTable();
}
}
class UniverseObjectBuilder extends fb.ObjectBuilder {
final double? _age;
final List<GalaxyObjectBuilder>? _galaxies;
UniverseObjectBuilder({
double? age,
List<GalaxyObjectBuilder>? galaxies,
})
: _age = age,
_galaxies = galaxies;
/// Finish building, and store into the [fbBuilder].
@override
int finish(fb.Builder fbBuilder) {
final int? galaxiesOffset = _galaxies == null ? null
: fbBuilder.writeList(_galaxies!.map((b) => b.getOrCreateOffset(fbBuilder)).toList());
fbBuilder.startTable(2);
fbBuilder.addFloat64(0, _age);
fbBuilder.addOffset(1, galaxiesOffset);
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
Uint8List toBytes([String? fileIdentifier]) {
final fbBuilder = fb.Builder(deduplicateTables: false);
fbBuilder.finish(finish(fbBuilder), fileIdentifier);
return fbBuilder.buffer;
}
}

10
goldens/dart/generate.py Normal file
View File

@@ -0,0 +1,10 @@
from golden_utils import flatc_golden
def flatc(options, schema):
# Wrap the golden flatc generator with Dart specifics
flatc_golden(options=["--dart"] + options, schema=schema, prefix="dart")
def GenerateDart():
flatc([], "basic.fbs")

32
goldens/generate_goldens.py Executable file
View File

@@ -0,0 +1,32 @@
#!/usr/bin/env python3
from cpp.generate import GenerateCpp
from csharp.generate import GenerateCSharp
from dart.generate import GenerateDart
from go.generate import GenerateGo
from java.generate import GenerateJava
from kotlin.generate import GenerateKotlin
from lobster.generate import GenerateLobster
from lua.generate import GenerateLua
from nim.generate import GenerateNim
from php.generate import GeneratePhp
from py.generate import GeneratePython
from rust.generate import GenerateRust
from swift.generate import GenerateSwift
from ts.generate import GenerateTs
# Run each language generation logic
GenerateCpp()
GenerateCSharp()
GenerateDart()
GenerateGo()
GenerateJava()
GenerateKotlin()
GenerateLobster()
GenerateLua()
GenerateNim()
GeneratePhp()
GeneratePython()
GenerateRust()
GenerateSwift()
GenerateTs()

64
goldens/go/Galaxy.go Normal file
View File

@@ -0,0 +1,64 @@
// Code generated by the FlatBuffers compiler. DO NOT EDIT.
package Galaxy
import (
flatbuffers "github.com/google/flatbuffers/go"
)
type Galaxy struct {
_tab flatbuffers.Table
}
func GetRootAsGalaxy(buf []byte, offset flatbuffers.UOffsetT) *Galaxy {
n := flatbuffers.GetUOffsetT(buf[offset:])
x := &Galaxy{}
x.Init(buf, n+offset)
return x
}
func FinishGalaxyBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) {
builder.Finish(offset)
}
func GetSizePrefixedRootAsGalaxy(buf []byte, offset flatbuffers.UOffsetT) *Galaxy {
n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:])
x := &Galaxy{}
x.Init(buf, n+offset+flatbuffers.SizeUint32)
return x
}
func FinishSizePrefixedGalaxyBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) {
builder.FinishSizePrefixed(offset)
}
func (rcv *Galaxy) Init(buf []byte, i flatbuffers.UOffsetT) {
rcv._tab.Bytes = buf
rcv._tab.Pos = i
}
func (rcv *Galaxy) Table() flatbuffers.Table {
return rcv._tab
}
func (rcv *Galaxy) NumStars() int64 {
o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
if o != 0 {
return rcv._tab.GetInt64(o + rcv._tab.Pos)
}
return 0
}
func (rcv *Galaxy) MutateNumStars(n int64) bool {
return rcv._tab.MutateInt64Slot(4, n)
}
func GalaxyStart(builder *flatbuffers.Builder) {
builder.StartObject(1)
}
func GalaxyAddNumStars(builder *flatbuffers.Builder, numStars int64) {
builder.PrependInt64Slot(0, numStars, 0)
}
func GalaxyEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
return builder.EndObject()
}

90
goldens/go/Universe.go Normal file
View File

@@ -0,0 +1,90 @@
// Code generated by the FlatBuffers compiler. DO NOT EDIT.
package Universe
import (
flatbuffers "github.com/google/flatbuffers/go"
)
type Universe struct {
_tab flatbuffers.Table
}
func GetRootAsUniverse(buf []byte, offset flatbuffers.UOffsetT) *Universe {
n := flatbuffers.GetUOffsetT(buf[offset:])
x := &Universe{}
x.Init(buf, n+offset)
return x
}
func FinishUniverseBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) {
builder.Finish(offset)
}
func GetSizePrefixedRootAsUniverse(buf []byte, offset flatbuffers.UOffsetT) *Universe {
n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:])
x := &Universe{}
x.Init(buf, n+offset+flatbuffers.SizeUint32)
return x
}
func FinishSizePrefixedUniverseBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) {
builder.FinishSizePrefixed(offset)
}
func (rcv *Universe) Init(buf []byte, i flatbuffers.UOffsetT) {
rcv._tab.Bytes = buf
rcv._tab.Pos = i
}
func (rcv *Universe) Table() flatbuffers.Table {
return rcv._tab
}
func (rcv *Universe) Age() float64 {
o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
if o != 0 {
return rcv._tab.GetFloat64(o + rcv._tab.Pos)
}
return 0.0
}
func (rcv *Universe) MutateAge(n float64) bool {
return rcv._tab.MutateFloat64Slot(4, n)
}
func (rcv *Universe) Galaxies(obj *Galaxy, j int) bool {
o := flatbuffers.UOffsetT(rcv._tab.Offset(6))
if o != 0 {
x := rcv._tab.Vector(o)
x += flatbuffers.UOffsetT(j) * 4
x = rcv._tab.Indirect(x)
obj.Init(rcv._tab.Bytes, x)
return true
}
return false
}
func (rcv *Universe) GalaxiesLength() int {
o := flatbuffers.UOffsetT(rcv._tab.Offset(6))
if o != 0 {
return rcv._tab.VectorLen(o)
}
return 0
}
func UniverseStart(builder *flatbuffers.Builder) {
builder.StartObject(2)
}
func UniverseAddAge(builder *flatbuffers.Builder, age float64) {
builder.PrependFloat64Slot(0, age, 0.0)
}
func UniverseAddGalaxies(builder *flatbuffers.Builder, galaxies flatbuffers.UOffsetT) {
builder.PrependUOffsetTSlot(1, flatbuffers.UOffsetT(galaxies), 0)
}
func UniverseStartGalaxiesVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT {
return builder.StartVector(4, numElems, 4)
}
func UniverseEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
return builder.EndObject()
}

10
goldens/go/generate.py Normal file
View File

@@ -0,0 +1,10 @@
from golden_utils import flatc_golden
def flatc(options, schema):
# Wrap the golden flatc generator with Go specifics
flatc_golden(options=["--go"] + options, schema=schema, prefix="go")
def GenerateGo():
flatc([], "basic.fbs")

30
goldens/golden_utils.py Normal file
View File

@@ -0,0 +1,30 @@
import sys
from pathlib import Path
# Get the path where this script is located so we can invoke the script from
# any directory and have the paths work correctly.
script_path = Path(__file__).parent.resolve()
# Get the root path as an absolute path, so all derived paths are absolute.
root_path = script_path.parent.absolute()
# Get the location of the schema
schema_path = Path(script_path, "schema")
# Too add the util package in /scripts/util.py
sys.path.append(str(root_path.absolute()))
from scripts.util import flatc
def flatc_golden(options, schema, prefix):
# wrap the generic flatc call with specifis for these goldens.
flatc(
options=options,
# where the files are generated, typically the language (e.g. "cpp").
prefix=prefix,
# The schema are relative to the schema directory.
schema=str(Path(schema_path, schema)),
# Run flatc from this location.
cwd=script_path,
)

51
goldens/java/Galaxy.java Normal file
View File

@@ -0,0 +1,51 @@
// automatically generated by the FlatBuffers compiler, do not modify
import com.google.flatbuffers.BaseVector;
import com.google.flatbuffers.BooleanVector;
import com.google.flatbuffers.ByteVector;
import com.google.flatbuffers.Constants;
import com.google.flatbuffers.DoubleVector;
import com.google.flatbuffers.FlatBufferBuilder;
import com.google.flatbuffers.FloatVector;
import com.google.flatbuffers.IntVector;
import com.google.flatbuffers.LongVector;
import com.google.flatbuffers.ShortVector;
import com.google.flatbuffers.StringVector;
import com.google.flatbuffers.Struct;
import com.google.flatbuffers.Table;
import com.google.flatbuffers.UnionVector;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@SuppressWarnings("unused")
public final class Galaxy extends Table {
public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_26(); }
public static Galaxy getRootAsGalaxy(ByteBuffer _bb) { return getRootAsGalaxy(_bb, new Galaxy()); }
public static Galaxy getRootAsGalaxy(ByteBuffer _bb, Galaxy obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
public Galaxy __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
public long numStars() { int o = __offset(4); return o != 0 ? bb.getLong(o + bb_pos) : 0L; }
public static int createGalaxy(FlatBufferBuilder builder,
long numStars) {
builder.startTable(1);
Galaxy.addNumStars(builder, numStars);
return Galaxy.endGalaxy(builder);
}
public static void startGalaxy(FlatBufferBuilder builder) { builder.startTable(1); }
public static void addNumStars(FlatBufferBuilder builder, long numStars) { builder.addLong(0, numStars, 0L); }
public static int endGalaxy(FlatBufferBuilder builder) {
int o = builder.endTable();
return o;
}
public static final class Vector extends BaseVector {
public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; }
public Galaxy get(int j) { return get(new Galaxy(), j); }
public Galaxy get(Galaxy obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); }
}
}

View File

@@ -0,0 +1,63 @@
// automatically generated by the FlatBuffers compiler, do not modify
import com.google.flatbuffers.BaseVector;
import com.google.flatbuffers.BooleanVector;
import com.google.flatbuffers.ByteVector;
import com.google.flatbuffers.Constants;
import com.google.flatbuffers.DoubleVector;
import com.google.flatbuffers.FlatBufferBuilder;
import com.google.flatbuffers.FloatVector;
import com.google.flatbuffers.IntVector;
import com.google.flatbuffers.LongVector;
import com.google.flatbuffers.ShortVector;
import com.google.flatbuffers.StringVector;
import com.google.flatbuffers.Struct;
import com.google.flatbuffers.Table;
import com.google.flatbuffers.UnionVector;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@SuppressWarnings("unused")
public final class Universe extends Table {
public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_26(); }
public static Universe getRootAsUniverse(ByteBuffer _bb) { return getRootAsUniverse(_bb, new Universe()); }
public static Universe getRootAsUniverse(ByteBuffer _bb, Universe obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
public Universe __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
public double age() { int o = __offset(4); return o != 0 ? bb.getDouble(o + bb_pos) : 0.0; }
public Galaxy galaxies(int j) { return galaxies(new Galaxy(), j); }
public Galaxy galaxies(Galaxy obj, int j) { int o = __offset(6); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; }
public int galaxiesLength() { int o = __offset(6); return o != 0 ? __vector_len(o) : 0; }
public Galaxy.Vector galaxiesVector() { return galaxiesVector(new Galaxy.Vector()); }
public Galaxy.Vector galaxiesVector(Galaxy.Vector obj) { int o = __offset(6); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; }
public static int createUniverse(FlatBufferBuilder builder,
double age,
int galaxiesOffset) {
builder.startTable(2);
Universe.addAge(builder, age);
Universe.addGalaxies(builder, galaxiesOffset);
return Universe.endUniverse(builder);
}
public static void startUniverse(FlatBufferBuilder builder) { builder.startTable(2); }
public static void addAge(FlatBufferBuilder builder, double age) { builder.addDouble(0, age, 0.0); }
public static void addGalaxies(FlatBufferBuilder builder, int galaxiesOffset) { builder.addOffset(1, galaxiesOffset, 0); }
public static int createGalaxiesVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); }
public static void startGalaxiesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); }
public static int endUniverse(FlatBufferBuilder builder) {
int o = builder.endTable();
return o;
}
public static void finishUniverseBuffer(FlatBufferBuilder builder, int offset) { builder.finish(offset); }
public static void finishSizePrefixedUniverseBuffer(FlatBufferBuilder builder, int offset) { builder.finishSizePrefixed(offset); }
public static final class Vector extends BaseVector {
public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; }
public Universe get(int j) { return get(new Universe(), j); }
public Universe get(Universe obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); }
}
}

10
goldens/java/generate.py Normal file
View File

@@ -0,0 +1,10 @@
from golden_utils import flatc_golden
def flatc(options, schema):
# Wrap the golden flatc generator with Java specifics
flatc_golden(options=["--java"] + options, schema=schema, prefix="java")
def GenerateJava():
flatc([], "basic.fbs")

53
goldens/kotlin/Galaxy.kt Normal file
View File

@@ -0,0 +1,53 @@
// automatically generated by the FlatBuffers compiler, do not modify
import com.google.flatbuffers.BaseVector
import com.google.flatbuffers.BooleanVector
import com.google.flatbuffers.ByteVector
import com.google.flatbuffers.Constants
import com.google.flatbuffers.DoubleVector
import com.google.flatbuffers.FlatBufferBuilder
import com.google.flatbuffers.FloatVector
import com.google.flatbuffers.LongVector
import com.google.flatbuffers.StringVector
import com.google.flatbuffers.Struct
import com.google.flatbuffers.Table
import com.google.flatbuffers.UnionVector
import java.nio.ByteBuffer
import java.nio.ByteOrder
import kotlin.math.sign
@Suppress("unused")
class Galaxy : Table() {
fun __init(_i: Int, _bb: ByteBuffer) {
__reset(_i, _bb)
}
fun __assign(_i: Int, _bb: ByteBuffer) : Galaxy {
__init(_i, _bb)
return this
}
val numStars : Long
get() {
val o = __offset(4)
return if(o != 0) bb.getLong(o + bb_pos) else 0L
}
companion object {
fun validateVersion() = Constants.FLATBUFFERS_23_5_26()
fun getRootAsGalaxy(_bb: ByteBuffer): Galaxy = getRootAsGalaxy(_bb, Galaxy())
fun getRootAsGalaxy(_bb: ByteBuffer, obj: Galaxy): Galaxy {
_bb.order(ByteOrder.LITTLE_ENDIAN)
return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb))
}
fun createGalaxy(builder: FlatBufferBuilder, numStars: Long) : Int {
builder.startTable(1)
addNumStars(builder, numStars)
return endGalaxy(builder)
}
fun startGalaxy(builder: FlatBufferBuilder) = builder.startTable(1)
fun addNumStars(builder: FlatBufferBuilder, numStars: Long) = builder.addLong(0, numStars, 0L)
fun endGalaxy(builder: FlatBufferBuilder) : Int {
val o = builder.endTable()
return o
}
}
}

View File

@@ -0,0 +1,78 @@
// automatically generated by the FlatBuffers compiler, do not modify
import com.google.flatbuffers.BaseVector
import com.google.flatbuffers.BooleanVector
import com.google.flatbuffers.ByteVector
import com.google.flatbuffers.Constants
import com.google.flatbuffers.DoubleVector
import com.google.flatbuffers.FlatBufferBuilder
import com.google.flatbuffers.FloatVector
import com.google.flatbuffers.LongVector
import com.google.flatbuffers.StringVector
import com.google.flatbuffers.Struct
import com.google.flatbuffers.Table
import com.google.flatbuffers.UnionVector
import java.nio.ByteBuffer
import java.nio.ByteOrder
import kotlin.math.sign
@Suppress("unused")
class Universe : Table() {
fun __init(_i: Int, _bb: ByteBuffer) {
__reset(_i, _bb)
}
fun __assign(_i: Int, _bb: ByteBuffer) : Universe {
__init(_i, _bb)
return this
}
val age : Double
get() {
val o = __offset(4)
return if(o != 0) bb.getDouble(o + bb_pos) else 0.0
}
fun galaxies(j: Int) : Galaxy? = galaxies(Galaxy(), j)
fun galaxies(obj: Galaxy, j: Int) : Galaxy? {
val o = __offset(6)
return if (o != 0) {
obj.__assign(__indirect(__vector(o) + j * 4), bb)
} else {
null
}
}
val galaxiesLength : Int
get() {
val o = __offset(6); return if (o != 0) __vector_len(o) else 0
}
companion object {
fun validateVersion() = Constants.FLATBUFFERS_23_5_26()
fun getRootAsUniverse(_bb: ByteBuffer): Universe = getRootAsUniverse(_bb, Universe())
fun getRootAsUniverse(_bb: ByteBuffer, obj: Universe): Universe {
_bb.order(ByteOrder.LITTLE_ENDIAN)
return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb))
}
fun createUniverse(builder: FlatBufferBuilder, age: Double, galaxiesOffset: Int) : Int {
builder.startTable(2)
addAge(builder, age)
addGalaxies(builder, galaxiesOffset)
return endUniverse(builder)
}
fun startUniverse(builder: FlatBufferBuilder) = builder.startTable(2)
fun addAge(builder: FlatBufferBuilder, age: Double) = builder.addDouble(0, age, 0.0)
fun addGalaxies(builder: FlatBufferBuilder, galaxies: Int) = builder.addOffset(1, galaxies, 0)
fun createGalaxiesVector(builder: FlatBufferBuilder, data: IntArray) : Int {
builder.startVector(4, data.size, 4)
for (i in data.size - 1 downTo 0) {
builder.addOffset(data[i])
}
return builder.endVector()
}
fun startGalaxiesVector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(4, numElems, 4)
fun endUniverse(builder: FlatBufferBuilder) : Int {
val o = builder.endTable()
return o
}
fun finishUniverseBuffer(builder: FlatBufferBuilder, offset: Int) = builder.finish(offset)
fun finishSizePrefixedUniverseBuffer(builder: FlatBufferBuilder, offset: Int) = builder.finishSizePrefixed(offset)
}
}

View File

@@ -0,0 +1,10 @@
from golden_utils import flatc_golden
def flatc(options, schema):
# Wrap the golden flatc generator with Kotlin specifics
flatc_golden(options=["--kotlin"] + options, schema=schema, prefix="kotlin")
def GenerateKotlin():
flatc([], "basic.fbs")

View File

@@ -0,0 +1,55 @@
// automatically generated by the FlatBuffers compiler, do not modify
import flatbuffers
class Galaxy
class Universe
class Galaxy : flatbuffers_handle
def num_stars() -> int:
return buf_.flatbuffers_field_int64(pos_, 4, 0)
def GetRootAsGalaxy(buf:string): return Galaxy { buf, buf.flatbuffers_indirect(0) }
struct GalaxyBuilder:
b_:flatbuffers_builder
def start():
b_.StartObject(1)
return this
def add_num_stars(num_stars:int):
b_.PrependInt64Slot(0, num_stars, 0)
return this
def end():
return b_.EndObject()
class Universe : flatbuffers_handle
def age() -> float:
return buf_.flatbuffers_field_float64(pos_, 4, 0.0)
def galaxies(i:int) -> Galaxy:
return Galaxy { buf_, buf_.flatbuffers_indirect(buf_.flatbuffers_field_vector(pos_, 6) + i * 4) }
def galaxies_length() -> int:
return buf_.flatbuffers_field_vector_len(pos_, 6)
def GetRootAsUniverse(buf:string): return Universe { buf, buf.flatbuffers_indirect(0) }
struct UniverseBuilder:
b_:flatbuffers_builder
def start():
b_.StartObject(2)
return this
def add_age(age:float):
b_.PrependFloat64Slot(0, age, 0.0)
return this
def add_galaxies(galaxies:flatbuffers_offset):
b_.PrependUOffsetTRelativeSlot(1, galaxies)
return this
def end():
return b_.EndObject()
def UniverseStartGalaxiesVector(b_:flatbuffers_builder, n_:int):
b_.StartVector(4, n_, 4)
def UniverseCreateGalaxiesVector(b_:flatbuffers_builder, v_:[flatbuffers_offset]):
b_.StartVector(4, v_.length, 4)
reverse(v_) e_: b_.PrependUOffsetTRelative(e_)
return b_.EndVector(v_.length)

View File

@@ -0,0 +1,10 @@
from golden_utils import flatc_golden
def flatc(options, schema):
# Wrap the golden flatc generator with Lobster specifics
flatc_golden(options=["--lobster"] + options, schema=schema, prefix="lobster")
def GenerateLobster():
flatc([], "basic.fbs")

48
goldens/lua/Galaxy.lua Normal file
View File

@@ -0,0 +1,48 @@
--[[ Galaxy
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 23.5.9
Declared by : //basic.fbs
Rooting type : Universe (//basic.fbs)
--]]
local flatbuffers = require('flatbuffers')
local Galaxy = {}
local mt = {}
function Galaxy.New()
local o = {}
setmetatable(o, {__index = mt})
return o
end
function mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function mt:NumStars()
local o = self.view:Offset(4)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Int64, self.view.pos + o)
end
return 0
end
function Galaxy.Start(builder)
builder:StartObject(1)
end
function Galaxy.AddNumStars(builder, numStars)
builder:PrependInt64Slot(0, numStars, 0)
end
function Galaxy.End(builder)
return builder:EndObject()
end
return Galaxy

88
goldens/lua/Universe.lua Normal file
View File

@@ -0,0 +1,88 @@
--[[ Universe
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 23.5.9
Declared by : //basic.fbs
Rooting type : Universe (//basic.fbs)
--]]
local __Galaxy = require('Galaxy')
local flatbuffers = require('flatbuffers')
local Universe = {}
local mt = {}
function Universe.New()
local o = {}
setmetatable(o, {__index = mt})
return o
end
function Universe.GetRootAsUniverse(buf, offset)
if type(buf) == "string" then
buf = flatbuffers.binaryArray.New(buf)
end
local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)
local o = Universe.New()
o:Init(buf, n + offset)
return o
end
function mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function mt:Age()
local o = self.view:Offset(4)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Float64, self.view.pos + o)
end
return 0.0
end
function mt:Galaxies(j)
local o = self.view:Offset(6)
if o ~= 0 then
local x = self.view:Vector(o)
x = x + ((j-1) * 4)
x = self.view:Indirect(x)
local obj = __Galaxy.New()
obj:Init(self.view.bytes, x)
return obj
end
end
function mt:GalaxiesLength()
local o = self.view:Offset(6)
if o ~= 0 then
return self.view:VectorLen(o)
end
return 0
end
function Universe.Start(builder)
builder:StartObject(2)
end
function Universe.AddAge(builder, age)
builder:PrependFloat64Slot(0, age, 0.0)
end
function Universe.AddGalaxies(builder, galaxies)
builder:PrependUOffsetTRelativeSlot(1, galaxies, 0)
end
function Universe.StartGalaxiesVector(builder, numElems)
return builder:StartVector(4, numElems, 4)
end
function Universe.End(builder)
return builder:EndObject()
end
return Universe

10
goldens/lua/generate.py Normal file
View File

@@ -0,0 +1,10 @@
from golden_utils import flatc_golden
def flatc(options, schema):
# Wrap the golden flatc generator with Lua specifics
flatc_golden(options=["--lua"] + options, schema=schema, prefix="lua")
def GenerateLua():
flatc([], "basic.fbs")

26
goldens/nim/Galaxy.nim Normal file
View File

@@ -0,0 +1,26 @@
#[ Galaxy
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 23.5.9
Declared by : //basic.fbs
Rooting type : Universe (//basic.fbs)
]#
import flatbuffers
type Galaxy* = object of FlatObj
func numStars*(self: Galaxy): int64 =
let o = self.tab.Offset(4)
if o != 0:
return Get[int64](self.tab, self.tab.Pos + o)
return 0
func `numStars=`*(self: var Galaxy, n: int64): bool =
return self.tab.MutateSlot(4, n)
proc GalaxyStart*(builder: var Builder) =
builder.StartObject(1)
proc GalaxyAddnumStars*(builder: var Builder, numStars: int64) =
builder.PrependSlot(0, numStars, default(int64))
proc GalaxyEnd*(builder: var Builder): uoffset =
return builder.EndObject()

46
goldens/nim/Universe.nim Normal file
View File

@@ -0,0 +1,46 @@
#[ Universe
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 23.5.9
Declared by : //basic.fbs
Rooting type : Universe (//basic.fbs)
]#
import Galaxy as Galaxy
import flatbuffers
import std/options
type Universe* = object of FlatObj
func age*(self: Universe): float64 =
let o = self.tab.Offset(4)
if o != 0:
return Get[float64](self.tab, self.tab.Pos + o)
return 0.0
func `age=`*(self: var Universe, n: float64): bool =
return self.tab.MutateSlot(4, n)
func galaxiesLength*(self: Universe): int =
let o = self.tab.Offset(6)
if o != 0:
return self.tab.VectorLen(o)
func galaxies*(self: Universe, j: int): Galaxy.Galaxy =
let o = self.tab.Offset(6)
if o != 0:
var x = self.tab.Vector(o)
x += j.uoffset * 4.uoffset
return Galaxy.Galaxy(tab: Vtable(Bytes: self.tab.Bytes, Pos: x))
func galaxies*(self: Universe): seq[Galaxy.Galaxy] =
let len = self.galaxiesLength
for i in countup(0, len - 1):
result.add(self.galaxies(i))
proc UniverseStart*(builder: var Builder) =
builder.StartObject(2)
proc UniverseAddage*(builder: var Builder, age: float64) =
builder.PrependSlot(0, age, default(float64))
proc UniverseAddgalaxies*(builder: var Builder, galaxies: uoffset) =
builder.PrependSlot(1, galaxies, default(uoffset))
proc UniverseStartgalaxiesVector*(builder: var Builder, numElems: uoffset) =
builder.StartVector(4, numElems, 4)
proc UniverseEnd*(builder: var Builder): uoffset =
return builder.EndObject()

10
goldens/nim/generate.py Normal file
View File

@@ -0,0 +1,10 @@
from golden_utils import flatc_golden
def flatc(options, schema):
# Wrap the golden flatc generator with Nim specifics
flatc_golden(options=["--nim"] + options, schema=schema, prefix="nim")
def GenerateNim():
flatc([], "basic.fbs")

82
goldens/php/Galaxy.php Normal file
View File

@@ -0,0 +1,82 @@
<?php
// automatically generated by the FlatBuffers compiler, do not modify
use \Google\FlatBuffers\Struct;
use \Google\FlatBuffers\Table;
use \Google\FlatBuffers\ByteBuffer;
use \Google\FlatBuffers\FlatBufferBuilder;
class Galaxy extends Table
{
/**
* @param ByteBuffer $bb
* @return Galaxy
*/
public static function getRootAsGalaxy(ByteBuffer $bb)
{
$obj = new Galaxy();
return ($obj->init($bb->getInt($bb->getPosition()) + $bb->getPosition(), $bb));
}
/**
* @param int $_i offset
* @param ByteBuffer $_bb
* @return Galaxy
**/
public function init($_i, ByteBuffer $_bb)
{
$this->bb_pos = $_i;
$this->bb = $_bb;
return $this;
}
/**
* @return long
*/
public function getNumStars()
{
$o = $this->__offset(4);
return $o != 0 ? $this->bb->getLong($o + $this->bb_pos) : 0;
}
/**
* @param FlatBufferBuilder $builder
* @return void
*/
public static function startGalaxy(FlatBufferBuilder $builder)
{
$builder->StartObject(1);
}
/**
* @param FlatBufferBuilder $builder
* @return Galaxy
*/
public static function createGalaxy(FlatBufferBuilder $builder, $num_stars)
{
$builder->startObject(1);
self::addNumStars($builder, $num_stars);
$o = $builder->endObject();
return $o;
}
/**
* @param FlatBufferBuilder $builder
* @param long
* @return void
*/
public static function addNumStars(FlatBufferBuilder $builder, $numStars)
{
$builder->addLongX(0, $numStars, 0);
}
/**
* @param FlatBufferBuilder $builder
* @return int table offset
*/
public static function endGalaxy(FlatBufferBuilder $builder)
{
$o = $builder->endObject();
return $o;
}
}

141
goldens/php/Universe.php Normal file
View File

@@ -0,0 +1,141 @@
<?php
// automatically generated by the FlatBuffers compiler, do not modify
use \Google\FlatBuffers\Struct;
use \Google\FlatBuffers\Table;
use \Google\FlatBuffers\ByteBuffer;
use \Google\FlatBuffers\FlatBufferBuilder;
class Universe extends Table
{
/**
* @param ByteBuffer $bb
* @return Universe
*/
public static function getRootAsUniverse(ByteBuffer $bb)
{
$obj = new Universe();
return ($obj->init($bb->getInt($bb->getPosition()) + $bb->getPosition(), $bb));
}
/**
* @param int $_i offset
* @param ByteBuffer $_bb
* @return Universe
**/
public function init($_i, ByteBuffer $_bb)
{
$this->bb_pos = $_i;
$this->bb = $_bb;
return $this;
}
/**
* @return double
*/
public function getAge()
{
$o = $this->__offset(4);
return $o != 0 ? $this->bb->getDouble($o + $this->bb_pos) : 0.0;
}
/**
* @returnVectorOffset
*/
public function getGalaxies($j)
{
$o = $this->__offset(6);
$obj = new Galaxy();
return $o != 0 ? $obj->init($this->__indirect($this->__vector($o) + $j * 4), $this->bb) : null;
}
/**
* @return int
*/
public function getGalaxiesLength()
{
$o = $this->__offset(6);
return $o != 0 ? $this->__vector_len($o) : 0;
}
/**
* @param FlatBufferBuilder $builder
* @return void
*/
public static function startUniverse(FlatBufferBuilder $builder)
{
$builder->StartObject(2);
}
/**
* @param FlatBufferBuilder $builder
* @return Universe
*/
public static function createUniverse(FlatBufferBuilder $builder, $age, $galaxies)
{
$builder->startObject(2);
self::addAge($builder, $age);
self::addGalaxies($builder, $galaxies);
$o = $builder->endObject();
return $o;
}
/**
* @param FlatBufferBuilder $builder
* @param double
* @return void
*/
public static function addAge(FlatBufferBuilder $builder, $age)
{
$builder->addDoubleX(0, $age, 0.0);
}
/**
* @param FlatBufferBuilder $builder
* @param VectorOffset
* @return void
*/
public static function addGalaxies(FlatBufferBuilder $builder, $galaxies)
{
$builder->addOffsetX(1, $galaxies, 0);
}
/**
* @param FlatBufferBuilder $builder
* @param array offset array
* @return int vector offset
*/
public static function createGalaxiesVector(FlatBufferBuilder $builder, array $data)
{
$builder->startVector(4, count($data), 4);
for ($i = count($data) - 1; $i >= 0; $i--) {
$builder->putOffset($data[$i]);
}
return $builder->endVector();
}
/**
* @param FlatBufferBuilder $builder
* @param int $numElems
* @return void
*/
public static function startGalaxiesVector(FlatBufferBuilder $builder, $numElems)
{
$builder->startVector(4, $numElems, 4);
}
/**
* @param FlatBufferBuilder $builder
* @return int table offset
*/
public static function endUniverse(FlatBufferBuilder $builder)
{
$o = $builder->endObject();
return $o;
}
public static function finishUniverseBuffer(FlatBufferBuilder $builder, $offset)
{
$builder->finish($offset);
}
}

10
goldens/php/generate.py Normal file
View File

@@ -0,0 +1,10 @@
from golden_utils import flatc_golden
def flatc(options, schema):
# Wrap the golden flatc generator with PHP specifics
flatc_golden(options=["--php"] + options, schema=schema, prefix="php")
def GeneratePhp():
flatc([], "basic.fbs")

50
goldens/py/Galaxy.py Normal file
View File

@@ -0,0 +1,50 @@
# automatically generated by the FlatBuffers compiler, do not modify
# namespace:
import flatbuffers
from flatbuffers.compat import import_numpy
np = import_numpy()
class Galaxy(object):
__slots__ = ['_tab']
@classmethod
def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = Galaxy()
x.Init(buf, n + offset)
return x
@classmethod
def GetRootAsGalaxy(cls, buf, offset=0):
"""This method is deprecated. Please switch to GetRootAs."""
return cls.GetRootAs(buf, offset)
# Galaxy
def Init(self, buf, pos):
self._tab = flatbuffers.table.Table(buf, pos)
# Galaxy
def NumStars(self):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
if o != 0:
return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos)
return 0
def GalaxyStart(builder):
builder.StartObject(1)
def Start(builder):
GalaxyStart(builder)
def GalaxyAddNumStars(builder, numStars):
builder.PrependInt64Slot(0, numStars, 0)
def AddNumStars(builder: flatbuffers.Builder, numStars: int):
GalaxyAddNumStars(builder, numStars)
def GalaxyEnd(builder):
return builder.EndObject()
def End(builder):
return GalaxyEnd(builder)

87
goldens/py/Universe.py Normal file
View File

@@ -0,0 +1,87 @@
# automatically generated by the FlatBuffers compiler, do not modify
# namespace:
import flatbuffers
from flatbuffers.compat import import_numpy
np = import_numpy()
class Universe(object):
__slots__ = ['_tab']
@classmethod
def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = Universe()
x.Init(buf, n + offset)
return x
@classmethod
def GetRootAsUniverse(cls, buf, offset=0):
"""This method is deprecated. Please switch to GetRootAs."""
return cls.GetRootAs(buf, offset)
# Universe
def Init(self, buf, pos):
self._tab = flatbuffers.table.Table(buf, pos)
# Universe
def Age(self):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
if o != 0:
return self._tab.Get(flatbuffers.number_types.Float64Flags, o + self._tab.Pos)
return 0.0
# Universe
def Galaxies(self, j):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
if o != 0:
x = self._tab.Vector(o)
x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
x = self._tab.Indirect(x)
from .Galaxy import Galaxy
obj = Galaxy()
obj.Init(self._tab.Bytes, x)
return obj
return None
# Universe
def GalaxiesLength(self):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
if o != 0:
return self._tab.VectorLen(o)
return 0
# Universe
def GalaxiesIsNone(self):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
return o == 0
def UniverseStart(builder):
builder.StartObject(2)
def Start(builder):
UniverseStart(builder)
def UniverseAddAge(builder, age):
builder.PrependFloat64Slot(0, age, 0.0)
def AddAge(builder: flatbuffers.Builder, age: float):
UniverseAddAge(builder, age)
def UniverseAddGalaxies(builder, galaxies):
builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(galaxies), 0)
def AddGalaxies(builder: flatbuffers.Builder, galaxies: int):
UniverseAddGalaxies(builder, galaxies)
def UniverseStartGalaxiesVector(builder, numElems):
return builder.StartVector(4, numElems, 4)
def StartGalaxiesVector(builder, numElems: int) -> int:
return UniverseStartGalaxiesVector(builder, numElems)
def UniverseEnd(builder):
return builder.EndObject()
def End(builder):
return UniverseEnd(builder)

0
goldens/py/__init__.py Normal file
View File

10
goldens/py/generate.py Normal file
View File

@@ -0,0 +1,10 @@
from golden_utils import flatc_golden
def flatc(options, schema):
# Wrap the golden flatc generator with Python specifics
flatc_golden(options=["--python"] + options, schema=schema, prefix="py")
def GeneratePython():
flatc([], "basic.fbs")

View File

@@ -0,0 +1,293 @@
// automatically generated by the FlatBuffers compiler, do not modify
// @generated
use core::mem;
use core::cmp::Ordering;
extern crate flatbuffers;
use self::flatbuffers::{EndianScalar, Follow};
pub enum GalaxyOffset {}
#[derive(Copy, Clone, PartialEq)]
pub struct Galaxy<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for Galaxy<'a> {
type Inner = Galaxy<'a>;
#[inline]
unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self { _tab: flatbuffers::Table::new(buf, loc) }
}
}
impl<'a> Galaxy<'a> {
pub const VT_NUM_STARS: flatbuffers::VOffsetT = 4;
#[inline]
pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
Galaxy { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args GalaxyArgs
) -> flatbuffers::WIPOffset<Galaxy<'bldr>> {
let mut builder = GalaxyBuilder::new(_fbb);
builder.add_num_stars(args.num_stars);
builder.finish()
}
#[inline]
pub fn num_stars(&self) -> i64 {
// Safety:
// Created from valid Table for this object
// which contains a valid value in this slot
unsafe { self._tab.get::<i64>(Galaxy::VT_NUM_STARS, Some(0)).unwrap()}
}
}
impl flatbuffers::Verifiable for Galaxy<'_> {
#[inline]
fn run_verifier(
v: &mut flatbuffers::Verifier, pos: usize
) -> Result<(), flatbuffers::InvalidFlatbuffer> {
use self::flatbuffers::Verifiable;
v.visit_table(pos)?
.visit_field::<i64>("num_stars", Self::VT_NUM_STARS, false)?
.finish();
Ok(())
}
}
pub struct GalaxyArgs {
pub num_stars: i64,
}
impl<'a> Default for GalaxyArgs {
#[inline]
fn default() -> Self {
GalaxyArgs {
num_stars: 0,
}
}
}
pub struct GalaxyBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> GalaxyBuilder<'a, 'b> {
#[inline]
pub fn add_num_stars(&mut self, num_stars: i64) {
self.fbb_.push_slot::<i64>(Galaxy::VT_NUM_STARS, num_stars, 0);
}
#[inline]
pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> GalaxyBuilder<'a, 'b> {
let start = _fbb.start_table();
GalaxyBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<Galaxy<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
impl core::fmt::Debug for Galaxy<'_> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let mut ds = f.debug_struct("Galaxy");
ds.field("num_stars", &self.num_stars());
ds.finish()
}
}
pub enum UniverseOffset {}
#[derive(Copy, Clone, PartialEq)]
pub struct Universe<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for Universe<'a> {
type Inner = Universe<'a>;
#[inline]
unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self { _tab: flatbuffers::Table::new(buf, loc) }
}
}
impl<'a> Universe<'a> {
pub const VT_AGE: flatbuffers::VOffsetT = 4;
pub const VT_GALAXIES: flatbuffers::VOffsetT = 6;
#[inline]
pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
Universe { _tab: table }
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args UniverseArgs<'args>
) -> flatbuffers::WIPOffset<Universe<'bldr>> {
let mut builder = UniverseBuilder::new(_fbb);
builder.add_age(args.age);
if let Some(x) = args.galaxies { builder.add_galaxies(x); }
builder.finish()
}
#[inline]
pub fn age(&self) -> f64 {
// Safety:
// Created from valid Table for this object
// which contains a valid value in this slot
unsafe { self._tab.get::<f64>(Universe::VT_AGE, Some(0.0)).unwrap()}
}
#[inline]
pub fn galaxies(&self) -> Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Galaxy<'a>>>> {
// Safety:
// Created from valid Table for this object
// which contains a valid value in this slot
unsafe { self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Galaxy>>>>(Universe::VT_GALAXIES, None)}
}
}
impl flatbuffers::Verifiable for Universe<'_> {
#[inline]
fn run_verifier(
v: &mut flatbuffers::Verifier, pos: usize
) -> Result<(), flatbuffers::InvalidFlatbuffer> {
use self::flatbuffers::Verifiable;
v.visit_table(pos)?
.visit_field::<f64>("age", Self::VT_AGE, false)?
.visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, flatbuffers::ForwardsUOffset<Galaxy>>>>("galaxies", Self::VT_GALAXIES, false)?
.finish();
Ok(())
}
}
pub struct UniverseArgs<'a> {
pub age: f64,
pub galaxies: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<Galaxy<'a>>>>>,
}
impl<'a> Default for UniverseArgs<'a> {
#[inline]
fn default() -> Self {
UniverseArgs {
age: 0.0,
galaxies: None,
}
}
}
pub struct UniverseBuilder<'a: 'b, 'b> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b> UniverseBuilder<'a, 'b> {
#[inline]
pub fn add_age(&mut self, age: f64) {
self.fbb_.push_slot::<f64>(Universe::VT_AGE, age, 0.0);
}
#[inline]
pub fn add_galaxies(&mut self, galaxies: flatbuffers::WIPOffset<flatbuffers::Vector<'b , flatbuffers::ForwardsUOffset<Galaxy<'b >>>>) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(Universe::VT_GALAXIES, galaxies);
}
#[inline]
pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> UniverseBuilder<'a, 'b> {
let start = _fbb.start_table();
UniverseBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<Universe<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
impl core::fmt::Debug for Universe<'_> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let mut ds = f.debug_struct("Universe");
ds.field("age", &self.age());
ds.field("galaxies", &self.galaxies());
ds.finish()
}
}
#[inline]
/// Verifies that a buffer of bytes contains a `Universe`
/// and returns it.
/// Note that verification is still experimental and may not
/// catch every error, or be maximally performant. For the
/// previous, unchecked, behavior use
/// `root_as_universe_unchecked`.
pub fn root_as_universe(buf: &[u8]) -> Result<Universe, flatbuffers::InvalidFlatbuffer> {
flatbuffers::root::<Universe>(buf)
}
#[inline]
/// Verifies that a buffer of bytes contains a size prefixed
/// `Universe` and returns it.
/// Note that verification is still experimental and may not
/// catch every error, or be maximally performant. For the
/// previous, unchecked, behavior use
/// `size_prefixed_root_as_universe_unchecked`.
pub fn size_prefixed_root_as_universe(buf: &[u8]) -> Result<Universe, flatbuffers::InvalidFlatbuffer> {
flatbuffers::size_prefixed_root::<Universe>(buf)
}
#[inline]
/// Verifies, with the given options, that a buffer of bytes
/// contains a `Universe` and returns it.
/// Note that verification is still experimental and may not
/// catch every error, or be maximally performant. For the
/// previous, unchecked, behavior use
/// `root_as_universe_unchecked`.
pub fn root_as_universe_with_opts<'b, 'o>(
opts: &'o flatbuffers::VerifierOptions,
buf: &'b [u8],
) -> Result<Universe<'b>, flatbuffers::InvalidFlatbuffer> {
flatbuffers::root_with_opts::<Universe<'b>>(opts, buf)
}
#[inline]
/// Verifies, with the given verifier options, that a buffer of
/// bytes contains a size prefixed `Universe` and returns
/// it. Note that verification is still experimental and may not
/// catch every error, or be maximally performant. For the
/// previous, unchecked, behavior use
/// `root_as_universe_unchecked`.
pub fn size_prefixed_root_as_universe_with_opts<'b, 'o>(
opts: &'o flatbuffers::VerifierOptions,
buf: &'b [u8],
) -> Result<Universe<'b>, flatbuffers::InvalidFlatbuffer> {
flatbuffers::size_prefixed_root_with_opts::<Universe<'b>>(opts, buf)
}
#[inline]
/// Assumes, without verification, that a buffer of bytes contains a Universe and returns it.
/// # Safety
/// Callers must trust the given bytes do indeed contain a valid `Universe`.
pub unsafe fn root_as_universe_unchecked(buf: &[u8]) -> Universe {
flatbuffers::root_unchecked::<Universe>(buf)
}
#[inline]
/// Assumes, without verification, that a buffer of bytes contains a size prefixed Universe and returns it.
/// # Safety
/// Callers must trust the given bytes do indeed contain a valid size prefixed `Universe`.
pub unsafe fn size_prefixed_root_as_universe_unchecked(buf: &[u8]) -> Universe {
flatbuffers::size_prefixed_root_unchecked::<Universe>(buf)
}
#[inline]
pub fn finish_universe_buffer<'a, 'b>(
fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,
root: flatbuffers::WIPOffset<Universe<'a>>) {
fbb.finish(root, None);
}
#[inline]
pub fn finish_size_prefixed_universe_buffer<'a, 'b>(fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>, root: flatbuffers::WIPOffset<Universe<'a>>) {
fbb.finish_size_prefixed(root, None);
}

10
goldens/rust/generate.py Normal file
View File

@@ -0,0 +1,10 @@
from golden_utils import flatc_golden
def flatc(options, schema):
# Wrap the golden flatc generator with Rust specifics
flatc_golden(options=["--rust"] + options, schema=schema, prefix="rust")
def GenerateRust():
flatc([], "basic.fbs")

13
goldens/schema/basic.fbs Normal file
View File

@@ -0,0 +1,13 @@
// This file should contain the basics of flatbuffers that all languages should
// support.
table Galaxy {
num_stars:long;
}
table Universe {
age:double;
galaxies:[Galaxy];
}
root_type Universe;

View File

@@ -0,0 +1,84 @@
// automatically generated by the FlatBuffers compiler, do not modify
// swiftlint:disable all
// swiftformat:disable all
import FlatBuffers
public struct Galaxy: FlatBufferObject, Verifiable {
static func validateVersion() { FlatBuffersVersion_23_5_26() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table
private init(_ t: Table) { _accessor = t }
public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
private enum VTOFFSET: VOffset {
case numStars = 4
var v: Int32 { Int32(self.rawValue) }
var p: VOffset { self.rawValue }
}
public var numStars: Int64 { let o = _accessor.offset(VTOFFSET.numStars.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) }
public static func startGalaxy(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) }
public static func add(numStars: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: numStars, def: 0, at: VTOFFSET.numStars.p) }
public static func endGalaxy(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end }
public static func createGalaxy(
_ fbb: inout FlatBufferBuilder,
numStars: Int64 = 0
) -> Offset {
let __start = Galaxy.startGalaxy(&fbb)
Galaxy.add(numStars: numStars, &fbb)
return Galaxy.endGalaxy(&fbb, start: __start)
}
public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
var _v = try verifier.visitTable(at: position)
try _v.visit(field: VTOFFSET.numStars.p, fieldName: "numStars", required: false, type: Int64.self)
_v.finish()
}
}
public struct Universe: FlatBufferObject, Verifiable {
static func validateVersion() { FlatBuffersVersion_23_5_26() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table
private init(_ t: Table) { _accessor = t }
public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
private enum VTOFFSET: VOffset {
case age = 4
case galaxies = 6
var v: Int32 { Int32(self.rawValue) }
var p: VOffset { self.rawValue }
}
public var age: Double { let o = _accessor.offset(VTOFFSET.age.v); return o == 0 ? 0.0 : _accessor.readBuffer(of: Double.self, at: o) }
public var hasGalaxies: Bool { let o = _accessor.offset(VTOFFSET.galaxies.v); return o == 0 ? false : true }
public var galaxiesCount: Int32 { let o = _accessor.offset(VTOFFSET.galaxies.v); return o == 0 ? 0 : _accessor.vector(count: o) }
public func galaxies(at index: Int32) -> Galaxy? { let o = _accessor.offset(VTOFFSET.galaxies.v); return o == 0 ? nil : Galaxy(_accessor.bb, o: _accessor.indirect(_accessor.vector(at: o) + index * 4)) }
public static func startUniverse(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 2) }
public static func add(age: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: age, def: 0.0, at: VTOFFSET.age.p) }
public static func addVectorOf(galaxies: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: galaxies, at: VTOFFSET.galaxies.p) }
public static func endUniverse(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end }
public static func createUniverse(
_ fbb: inout FlatBufferBuilder,
age: Double = 0.0,
galaxiesVectorOffset galaxies: Offset = Offset()
) -> Offset {
let __start = Universe.startUniverse(&fbb)
Universe.add(age: age, &fbb)
Universe.addVectorOf(galaxies: galaxies, &fbb)
return Universe.endUniverse(&fbb, start: __start)
}
public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
var _v = try verifier.visitTable(at: position)
try _v.visit(field: VTOFFSET.age.p, fieldName: "age", required: false, type: Double.self)
try _v.visit(field: VTOFFSET.galaxies.p, fieldName: "galaxies", required: false, type: ForwardOffset<Vector<ForwardOffset<Galaxy>, Galaxy>>.self)
_v.finish()
}
}

10
goldens/swift/generate.py Normal file
View File

@@ -0,0 +1,10 @@
from golden_utils import flatc_golden
def flatc(options, schema):
# Wrap the golden flatc generator with Swift specifics
flatc_golden(options=["--swift"] + options, schema=schema, prefix="swift")
def GenerateSwift():
flatc([], "basic.fbs")

4
goldens/ts/basic.ts Normal file
View File

@@ -0,0 +1,4 @@
// automatically generated by the FlatBuffers compiler, do not modify
export { Galaxy } from './galaxy.js';
export { Universe } from './universe.js';

46
goldens/ts/galaxy.ts Normal file
View File

@@ -0,0 +1,46 @@
// automatically generated by the FlatBuffers compiler, do not modify
import * as flatbuffers from 'flatbuffers';
export class Galaxy {
bb: flatbuffers.ByteBuffer|null = null;
bb_pos = 0;
__init(i:number, bb:flatbuffers.ByteBuffer):Galaxy {
this.bb_pos = i;
this.bb = bb;
return this;
}
static getRootAsGalaxy(bb:flatbuffers.ByteBuffer, obj?:Galaxy):Galaxy {
return (obj || new Galaxy()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
static getSizePrefixedRootAsGalaxy(bb:flatbuffers.ByteBuffer, obj?:Galaxy):Galaxy {
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
return (obj || new Galaxy()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
numStars():bigint {
const offset = this.bb!.__offset(this.bb_pos, 4);
return offset ? this.bb!.readInt64(this.bb_pos + offset) : BigInt('0');
}
static startGalaxy(builder:flatbuffers.Builder) {
builder.startObject(1);
}
static addNumStars(builder:flatbuffers.Builder, numStars:bigint) {
builder.addFieldInt64(0, numStars, BigInt('0'));
}
static endGalaxy(builder:flatbuffers.Builder):flatbuffers.Offset {
const offset = builder.endObject();
return offset;
}
static createGalaxy(builder:flatbuffers.Builder, numStars:bigint):flatbuffers.Offset {
Galaxy.startGalaxy(builder);
Galaxy.addNumStars(builder, numStars);
return Galaxy.endGalaxy(builder);
}
}

10
goldens/ts/generate.py Normal file
View File

@@ -0,0 +1,10 @@
from golden_utils import flatc_golden
def flatc(options, schema):
# Wrap the golden flatc generator with Swift specifics
flatc_golden(options=["--ts"] + options, schema=schema, prefix="ts")
def GenerateTs():
flatc([], "basic.fbs")

84
goldens/ts/universe.ts Normal file
View File

@@ -0,0 +1,84 @@
// automatically generated by the FlatBuffers compiler, do not modify
import * as flatbuffers from 'flatbuffers';
import { Galaxy } from './galaxy.js';
export class Universe {
bb: flatbuffers.ByteBuffer|null = null;
bb_pos = 0;
__init(i:number, bb:flatbuffers.ByteBuffer):Universe {
this.bb_pos = i;
this.bb = bb;
return this;
}
static getRootAsUniverse(bb:flatbuffers.ByteBuffer, obj?:Universe):Universe {
return (obj || new Universe()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
static getSizePrefixedRootAsUniverse(bb:flatbuffers.ByteBuffer, obj?:Universe):Universe {
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
return (obj || new Universe()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
age():number {
const offset = this.bb!.__offset(this.bb_pos, 4);
return offset ? this.bb!.readFloat64(this.bb_pos + offset) : 0.0;
}
galaxies(index: number, obj?:Galaxy):Galaxy|null {
const offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? (obj || new Galaxy()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null;
}
galaxiesLength():number {
const offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
}
static startUniverse(builder:flatbuffers.Builder) {
builder.startObject(2);
}
static addAge(builder:flatbuffers.Builder, age:number) {
builder.addFieldFloat64(0, age, 0.0);
}
static addGalaxies(builder:flatbuffers.Builder, galaxiesOffset:flatbuffers.Offset) {
builder.addFieldOffset(1, galaxiesOffset, 0);
}
static createGalaxiesVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset {
builder.startVector(4, data.length, 4);
for (let i = data.length - 1; i >= 0; i--) {
builder.addOffset(data[i]!);
}
return builder.endVector();
}
static startGalaxiesVector(builder:flatbuffers.Builder, numElems:number) {
builder.startVector(4, numElems, 4);
}
static endUniverse(builder:flatbuffers.Builder):flatbuffers.Offset {
const offset = builder.endObject();
return offset;
}
static finishUniverseBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) {
builder.finish(offset);
}
static finishSizePrefixedUniverseBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) {
builder.finish(offset, undefined, true);
}
static createUniverse(builder:flatbuffers.Builder, age:number, galaxiesOffset:flatbuffers.Offset):flatbuffers.Offset {
Universe.startUniverse(builder);
Universe.addAge(builder, age);
Universe.addGalaxies(builder, galaxiesOffset);
return Universe.endUniverse(builder);
}
}

View File

@@ -17,6 +17,10 @@ func GetRootAsHelloReply(buf []byte, offset flatbuffers.UOffsetT) *HelloReply {
return x
}
func FinishHelloReplyBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) {
builder.Finish(offset)
}
func GetSizePrefixedRootAsHelloReply(buf []byte, offset flatbuffers.UOffsetT) *HelloReply {
n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:])
x := &HelloReply{}
@@ -24,6 +28,10 @@ func GetSizePrefixedRootAsHelloReply(buf []byte, offset flatbuffers.UOffsetT) *H
return x
}
func FinishSizePrefixedHelloReplyBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) {
builder.FinishSizePrefixed(offset)
}
func (rcv *HelloReply) Init(buf []byte, i flatbuffers.UOffsetT) {
rcv._tab.Bytes = buf
rcv._tab.Pos = i

View File

@@ -17,6 +17,10 @@ func GetRootAsHelloRequest(buf []byte, offset flatbuffers.UOffsetT) *HelloReques
return x
}
func FinishHelloRequestBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) {
builder.Finish(offset)
}
func GetSizePrefixedRootAsHelloRequest(buf []byte, offset flatbuffers.UOffsetT) *HelloRequest {
n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:])
x := &HelloRequest{}
@@ -24,6 +28,10 @@ func GetSizePrefixedRootAsHelloRequest(buf []byte, offset flatbuffers.UOffsetT)
return x
}
func FinishSizePrefixedHelloRequestBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) {
builder.FinishSizePrefixed(offset)
}
func (rcv *HelloRequest) Init(buf []byte, i flatbuffers.UOffsetT) {
rcv._tab.Bytes = buf
rcv._tab.Pos = i

View File

@@ -31,12 +31,20 @@ class HelloReply(object):
return self._tab.String(o + self._tab.Pos)
return None
def HelloReplyStart(builder): builder.StartObject(1)
def HelloReplyStart(builder):
builder.StartObject(1)
def Start(builder):
return HelloReplyStart(builder)
def HelloReplyAddMessage(builder, message): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(message), 0)
HelloReplyStart(builder)
def HelloReplyAddMessage(builder, message):
builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(message), 0)
def AddMessage(builder, message):
return HelloReplyAddMessage(builder, message)
def HelloReplyEnd(builder): return builder.EndObject()
HelloReplyAddMessage(builder, message)
def HelloReplyEnd(builder):
return builder.EndObject()
def End(builder):
return HelloReplyEnd(builder)
return HelloReplyEnd(builder)

View File

@@ -31,12 +31,20 @@ class HelloRequest(object):
return self._tab.String(o + self._tab.Pos)
return None
def HelloRequestStart(builder): builder.StartObject(1)
def HelloRequestStart(builder):
builder.StartObject(1)
def Start(builder):
return HelloRequestStart(builder)
def HelloRequestAddName(builder, name): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0)
HelloRequestStart(builder)
def HelloRequestAddName(builder, name):
builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0)
def AddName(builder, name):
return HelloRequestAddName(builder, name)
def HelloRequestEnd(builder): return builder.EndObject()
HelloRequestAddName(builder, name)
def HelloRequestEnd(builder):
return builder.EndObject()
def End(builder):
return HelloRequestEnd(builder)
return HelloRequestEnd(builder)

View File

@@ -6,7 +6,7 @@ import FlatBuffers
public struct models_HelloReply: FlatBufferObject, Verifiable {
static func validateVersion() { FlatBuffersVersion_23_1_21() }
static func validateVersion() { FlatBuffersVersion_23_5_26() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table
@@ -53,7 +53,7 @@ extension models_HelloReply: Encodable {
public struct models_HelloRequest: FlatBufferObject, Verifiable {
static func validateVersion() { FlatBuffersVersion_23_1_21() }
static func validateVersion() { FlatBuffersVersion_23_5_26() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table

View File

@@ -4,6 +4,16 @@ package(
default_visibility = ["//visibility:public"],
)
filegroup(
name = "distribution",
srcs = [
"BUILD.bazel",
] + glob([
"*.cc",
"*.h",
]),
)
filegroup(
name = "common_headers",
srcs = [

View File

@@ -17,6 +17,7 @@
#ifndef FLATBUFFERS_ARRAY_H_
#define FLATBUFFERS_ARRAY_H_
#include <cstdint>
#include <memory>
#include "flatbuffers/base.h"
@@ -37,7 +38,7 @@ template<typename T, uint16_t length> class Array {
public:
typedef uint16_t size_type;
typedef typename IndirectHelper<IndirectHelperType>::return_type return_type;
typedef VectorConstIterator<T, return_type> const_iterator;
typedef VectorConstIterator<T, return_type, uoffset_t> const_iterator;
typedef VectorReverseIterator<const_iterator> const_reverse_iterator;
// If T is a LE-scalar or a struct (!scalar_tag::value).
@@ -158,11 +159,13 @@ template<typename T, uint16_t length> class Array {
// Specialization for Array[struct] with access using Offset<void> pointer.
// This specialization used by idl_gen_text.cpp.
template<typename T, uint16_t length> class Array<Offset<T>, length> {
template<typename T, uint16_t length, template<typename> class OffsetT>
class Array<OffsetT<T>, length> {
static_assert(flatbuffers::is_same<T, void>::value, "unexpected type T");
public:
typedef const void *return_type;
typedef uint16_t size_type;
const uint8_t *Data() const { return data_; }

View File

@@ -43,6 +43,7 @@
#include <vector>
#include <set>
#include <algorithm>
#include <limits>
#include <iterator>
#include <memory>
@@ -139,8 +140,8 @@
#endif // !defined(FLATBUFFERS_LITTLEENDIAN)
#define FLATBUFFERS_VERSION_MAJOR 23
#define FLATBUFFERS_VERSION_MINOR 1
#define FLATBUFFERS_VERSION_REVISION 21
#define FLATBUFFERS_VERSION_MINOR 5
#define FLATBUFFERS_VERSION_REVISION 26
#define FLATBUFFERS_STRING_EXPAND(X) #X
#define FLATBUFFERS_STRING(X) FLATBUFFERS_STRING_EXPAND(X)
namespace flatbuffers {
@@ -233,12 +234,17 @@ namespace flatbuffers {
}
#define FLATBUFFERS_HAS_STRING_VIEW 1
// Check for absl::string_view
#elif __has_include("absl/strings/string_view.h")
#include "absl/strings/string_view.h"
namespace flatbuffers {
typedef absl::string_view string_view;
}
#define FLATBUFFERS_HAS_STRING_VIEW 1
#elif __has_include("absl/strings/string_view.h") && \
__has_include("absl/base/config.h") && \
(__cplusplus >= 201411)
#include "absl/base/config.h"
#if !defined(ABSL_USES_STD_STRING_VIEW)
#include "absl/strings/string_view.h"
namespace flatbuffers {
typedef absl::string_view string_view;
}
#define FLATBUFFERS_HAS_STRING_VIEW 1
#endif
#endif
#endif // __has_include
#endif // !FLATBUFFERS_HAS_STRING_VIEW
@@ -273,14 +279,14 @@ namespace flatbuffers {
#endif // !FLATBUFFERS_LOCALE_INDEPENDENT
// Suppress Undefined Behavior Sanitizer (recoverable only). Usage:
// - __suppress_ubsan__("undefined")
// - __suppress_ubsan__("signed-integer-overflow")
// - FLATBUFFERS_SUPPRESS_UBSAN("undefined")
// - FLATBUFFERS_SUPPRESS_UBSAN("signed-integer-overflow")
#if defined(__clang__) && (__clang_major__ > 3 || (__clang_major__ == 3 && __clang_minor__ >=7))
#define __suppress_ubsan__(type) __attribute__((no_sanitize(type)))
#define FLATBUFFERS_SUPPRESS_UBSAN(type) __attribute__((no_sanitize(type)))
#elif defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__ >= 409)
#define __suppress_ubsan__(type) __attribute__((no_sanitize_undefined))
#define FLATBUFFERS_SUPPRESS_UBSAN(type) __attribute__((no_sanitize_undefined))
#else
#define __suppress_ubsan__(type)
#define FLATBUFFERS_SUPPRESS_UBSAN(type)
#endif
// This is constexpr function used for checking compile-time constants.
@@ -318,9 +324,11 @@ namespace flatbuffers {
// Also, using a consistent offset type maintains compatibility of serialized
// offset values between 32bit and 64bit systems.
typedef uint32_t uoffset_t;
typedef uint64_t uoffset64_t;
// Signed offsets for references that can go in both directions.
typedef int32_t soffset_t;
typedef int64_t soffset64_t;
// Offset/index used in v-tables, can be changed to uint8_t in
// format forks to save a bit of space if desired.
@@ -329,7 +337,8 @@ typedef uint16_t voffset_t;
typedef uintmax_t largest_scalar_t;
// In 32bits, this evaluates to 2GB - 1
#define FLATBUFFERS_MAX_BUFFER_SIZE ((1ULL << (sizeof(::flatbuffers::soffset_t) * 8 - 1)) - 1)
#define FLATBUFFERS_MAX_BUFFER_SIZE std::numeric_limits<::flatbuffers::soffset_t>::max()
#define FLATBUFFERS_MAX_64_BUFFER_SIZE std::numeric_limits<::flatbuffers::soffset64_t>::max()
// The minimum size buffer that can be a valid flatbuffer.
// Includes the offset to the root table (uoffset_t), the offset to the vtable
@@ -413,7 +422,7 @@ template<typename T> T EndianScalar(T t) {
template<typename T>
// UBSAN: C++ aliasing type rules, see std::bit_cast<> for details.
__suppress_ubsan__("alignment")
FLATBUFFERS_SUPPRESS_UBSAN("alignment")
T ReadScalar(const void *p) {
return EndianScalar(*reinterpret_cast<const T *>(p));
}
@@ -427,13 +436,13 @@ T ReadScalar(const void *p) {
template<typename T>
// UBSAN: C++ aliasing type rules, see std::bit_cast<> for details.
__suppress_ubsan__("alignment")
FLATBUFFERS_SUPPRESS_UBSAN("alignment")
void WriteScalar(void *p, T t) {
*reinterpret_cast<T *>(p) = EndianScalar(t);
}
template<typename T> struct Offset;
template<typename T> __suppress_ubsan__("alignment") void WriteScalar(void *p, Offset<T> t) {
template<typename T> FLATBUFFERS_SUPPRESS_UBSAN("alignment") void WriteScalar(void *p, Offset<T> t) {
*reinterpret_cast<uoffset_t *>(p) = EndianScalar(t.o);
}
@@ -444,7 +453,7 @@ template<typename T> __suppress_ubsan__("alignment") void WriteScalar(void *p, O
// Computes how many bytes you'd have to pad to be able to write an
// "scalar_size" scalar if the buffer had grown to "buf_size" (downwards in
// memory).
__suppress_ubsan__("unsigned-integer-overflow")
FLATBUFFERS_SUPPRESS_UBSAN("unsigned-integer-overflow")
inline size_t PaddingBytes(size_t buf_size, size_t scalar_size) {
return ((~buf_size) + 1) & (scalar_size - 1);
}

View File

@@ -25,14 +25,33 @@ namespace flatbuffers {
// Wrapper for uoffset_t to allow safe template specialization.
// Value is allowed to be 0 to indicate a null object (see e.g. AddOffset).
template<typename T> struct Offset {
uoffset_t o;
template<typename T = void> struct Offset {
// The type of offset to use.
typedef uoffset_t offset_type;
offset_type o;
Offset() : o(0) {}
Offset(uoffset_t _o) : o(_o) {}
Offset<void> Union() const { return Offset<void>(o); }
Offset(const offset_type _o) : o(_o) {}
Offset<> Union() const { return o; }
bool IsNull() const { return !o; }
};
// Wrapper for uoffset64_t Offsets.
template<typename T = void> struct Offset64 {
// The type of offset to use.
typedef uoffset64_t offset_type;
offset_type o;
Offset64() : o(0) {}
Offset64(const offset_type offset) : o(offset) {}
Offset64<> Union() const { return o; }
bool IsNull() const { return !o; }
};
// Litmus check for ensuring the Offsets are the expected size.
static_assert(sizeof(Offset<>) == 4, "Offset has wrong size");
static_assert(sizeof(Offset64<>) == 8, "Offset64 has wrong size");
inline void EndianCheck() {
int endiantest = 1;
// If this fails, see FLATBUFFERS_LITTLEENDIAN above.
@@ -75,35 +94,59 @@ template<typename T> struct IndirectHelper {
typedef T return_type;
typedef T mutable_return_type;
static const size_t element_stride = sizeof(T);
static return_type Read(const uint8_t *p, uoffset_t i) {
static return_type Read(const uint8_t *p, const size_t i) {
return EndianScalar((reinterpret_cast<const T *>(p))[i]);
}
static return_type Read(uint8_t *p, uoffset_t i) {
return Read(const_cast<const uint8_t *>(p), i);
static mutable_return_type Read(uint8_t *p, const size_t i) {
return reinterpret_cast<mutable_return_type>(
Read(const_cast<const uint8_t *>(p), i));
}
};
template<typename T> struct IndirectHelper<Offset<T>> {
// For vector of Offsets.
template<typename T, template<typename> class OffsetT>
struct IndirectHelper<OffsetT<T>> {
typedef const T *return_type;
typedef T *mutable_return_type;
static const size_t element_stride = sizeof(uoffset_t);
static return_type Read(const uint8_t *p, uoffset_t i) {
p += i * sizeof(uoffset_t);
return reinterpret_cast<return_type>(p + ReadScalar<uoffset_t>(p));
typedef typename OffsetT<T>::offset_type offset_type;
static const offset_type element_stride = sizeof(offset_type);
static return_type Read(const uint8_t *const p, const offset_type i) {
// Offsets are relative to themselves, so first update the pointer to
// point to the offset location.
const uint8_t *const offset_location = p + i * element_stride;
// Then read the scalar value of the offset (which may be 32 or 64-bits) and
// then determine the relative location from the offset location.
return reinterpret_cast<return_type>(
offset_location + ReadScalar<offset_type>(offset_location));
}
static mutable_return_type Read(uint8_t *p, uoffset_t i) {
p += i * sizeof(uoffset_t);
return reinterpret_cast<mutable_return_type>(p + ReadScalar<uoffset_t>(p));
static mutable_return_type Read(uint8_t *const p, const offset_type i) {
// Offsets are relative to themselves, so first update the pointer to
// point to the offset location.
uint8_t *const offset_location = p + i * element_stride;
// Then read the scalar value of the offset (which may be 32 or 64-bits) and
// then determine the relative location from the offset location.
return reinterpret_cast<mutable_return_type>(
offset_location + ReadScalar<offset_type>(offset_location));
}
};
// For vector of structs.
template<typename T> struct IndirectHelper<const T *> {
typedef const T *return_type;
typedef T *mutable_return_type;
static const size_t element_stride = sizeof(T);
static return_type Read(const uint8_t *p, uoffset_t i) {
return reinterpret_cast<return_type>(p + i * sizeof(T));
static return_type Read(const uint8_t *const p, const size_t i) {
// Structs are stored inline, relative to the first struct pointer.
return reinterpret_cast<return_type>(p + i * element_stride);
}
static mutable_return_type Read(uint8_t *p, uoffset_t i) {
return reinterpret_cast<mutable_return_type>(p + i * sizeof(T));
static mutable_return_type Read(uint8_t *const p, const size_t i) {
// Structs are stored inline, relative to the first struct pointer.
return reinterpret_cast<mutable_return_type>(p + i * element_stride);
}
};
@@ -130,23 +173,25 @@ inline bool BufferHasIdentifier(const void *buf, const char *identifier,
/// @cond FLATBUFFERS_INTERNAL
// Helpers to get a typed pointer to the root object contained in the buffer.
template<typename T> T *GetMutableRoot(void *buf) {
if (!buf) return nullptr;
EndianCheck();
return reinterpret_cast<T *>(
reinterpret_cast<uint8_t *>(buf) +
EndianScalar(*reinterpret_cast<uoffset_t *>(buf)));
}
template<typename T> T *GetMutableSizePrefixedRoot(void *buf) {
return GetMutableRoot<T>(reinterpret_cast<uint8_t *>(buf) +
sizeof(uoffset_t));
template<typename T, typename SizeT = uoffset_t>
T *GetMutableSizePrefixedRoot(void *buf) {
return GetMutableRoot<T>(reinterpret_cast<uint8_t *>(buf) + sizeof(SizeT));
}
template<typename T> const T *GetRoot(const void *buf) {
return GetMutableRoot<T>(const_cast<void *>(buf));
}
template<typename T> const T *GetSizePrefixedRoot(const void *buf) {
return GetRoot<T>(reinterpret_cast<const uint8_t *>(buf) + sizeof(uoffset_t));
template<typename T, typename SizeT = uoffset_t>
const T *GetSizePrefixedRoot(const void *buf) {
return GetRoot<T>(reinterpret_cast<const uint8_t *>(buf) + sizeof(SizeT));
}
} // namespace flatbuffers

View File

@@ -23,7 +23,11 @@
namespace flatbuffers {
// An code generator interface for producing converting flatbuffer schema into
struct CodeGenOptions {
std::string output_path;
};
// A code generator interface for producing converting flatbuffer schema into
// code.
class CodeGenerator {
public:
@@ -32,18 +36,32 @@ class CodeGenerator {
enum Status {
OK = 0,
ERROR = 1,
NOT_IMPLEMENTED = 2,
FAILED_VERIFICATION = 2,
NOT_IMPLEMENTED = 3
};
std::string status_detail;
// Generate code from the provided `parser`.
//
// DEPRECATED: prefer using the other overload of GenerateCode for bfbs.
virtual Status GenerateCode(const Parser &parser, const std::string &path,
const std::string &filename) = 0;
// Generate code from the provided `parser` and place it in the output.
virtual Status GenerateCodeString(const Parser &parser,
const std::string &filename,
std::string &output) {
(void)parser;
(void)filename;
(void)output;
return Status::NOT_IMPLEMENTED;
}
// Generate code from the provided `buffer` of given `length`. The buffer is a
// serialized reflection.fbs.
virtual Status GenerateCode(const uint8_t *buffer, int64_t length) = 0;
virtual Status GenerateCode(const uint8_t *buffer, int64_t length,
const CodeGenOptions &options) = 0;
virtual Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename,
@@ -52,11 +70,17 @@ class CodeGenerator {
virtual Status GenerateGrpcCode(const Parser &parser, const std::string &path,
const std::string &filename) = 0;
virtual Status GenerateRootFile(const Parser &parser,
const std::string &path) = 0;
virtual bool IsSchemaOnly() const = 0;
virtual bool SupportsBfbsGeneration() const = 0;
virtual bool SupportsRootFileGeneration() const = 0;
virtual IDLOptions::Language Language() const = 0;
virtual std::string LanguageName() const = 0;
protected:

View File

@@ -229,6 +229,10 @@ class TypedFloatConstantGenerator : public FloatConstantGenerator {
const std::string neg_inf_number_;
};
std::string JavaCSharpMakeRule(const bool java, const Parser &parser,
const std::string &path,
const std::string &file_name);
} // namespace flatbuffers
#endif // FLATBUFFERS_CODE_GENERATORS_H_

View File

@@ -0,0 +1,48 @@
/*
* Copyright 2023 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef FLATBUFFERS_FILE_MANAGER_H_
#define FLATBUFFERS_FILE_MANAGER_H_
#include <set>
#include <string>
#include "flatbuffers/util.h"
namespace flatbuffers {
// A File interface to write data to file by default or
// save only file names
class FileManager {
public:
FileManager() = default;
virtual ~FileManager() = default;
virtual bool SaveFile(const std::string &absolute_file_name,
const std::string &content) = 0;
virtual bool LoadFile(const std::string &absolute_file_name,
std::string *buf) = 0;
private:
// Copying is not supported.
FileManager(const FileManager &) = delete;
FileManager &operator=(const FileManager &) = delete;
};
} // namespace flatbuffers
#endif // FLATBUFFERS_FILE_MANAGER_H_

View File

@@ -18,12 +18,15 @@
#define FLATBUFFERS_FLATBUFFER_BUILDER_H_
#include <algorithm>
#include <cstdint>
#include <functional>
#include <initializer_list>
#include <type_traits>
#include "flatbuffers/allocator.h"
#include "flatbuffers/array.h"
#include "flatbuffers/base.h"
#include "flatbuffers/buffer.h"
#include "flatbuffers/buffer_ref.h"
#include "flatbuffers/default_allocator.h"
#include "flatbuffers/detached_buffer.h"
@@ -40,8 +43,9 @@ namespace flatbuffers {
// Converts a Field ID to a virtual table offset.
inline voffset_t FieldIndexToOffset(voffset_t field_id) {
// Should correspond to what EndTable() below builds up.
const int fixed_fields = 2; // Vtable size and Object Size.
return static_cast<voffset_t>((field_id + fixed_fields) * sizeof(voffset_t));
const voffset_t fixed_fields =
2 * sizeof(voffset_t); // Vtable size and Object Size.
return fixed_fields + field_id * sizeof(voffset_t);
}
template<typename T, typename Alloc = std::allocator<T>>
@@ -68,8 +72,13 @@ T *data(std::vector<T, Alloc> &v) {
/// `PushElement`/`AddElement`/`EndTable`, or the builtin `CreateString`/
/// `CreateVector` functions. Do this is depth-first order to build up a tree to
/// the root. `Finish()` wraps up the buffer ready for transport.
class FlatBufferBuilder {
template<bool Is64Aware = false> class FlatBufferBuilderImpl {
public:
// This switches the size type of the builder, based on if its 64-bit aware
// (uoffset64_t) or not (uoffset_t).
typedef
typename std::conditional<Is64Aware, uoffset64_t, uoffset_t>::type SizeT;
/// @brief Default constructor for FlatBufferBuilder.
/// @param[in] initial_size The initial size of the buffer, in bytes. Defaults
/// to `1024`.
@@ -81,13 +90,16 @@ class FlatBufferBuilder {
/// minimum alignment upon reallocation. Only needed if you intend to store
/// types with custom alignment AND you wish to read the buffer in-place
/// directly after creation.
explicit FlatBufferBuilder(
explicit FlatBufferBuilderImpl(
size_t initial_size = 1024, Allocator *allocator = nullptr,
bool own_allocator = false,
size_t buffer_minalign = AlignOf<largest_scalar_t>())
: buf_(initial_size, allocator, own_allocator, buffer_minalign),
: buf_(initial_size, allocator, own_allocator, buffer_minalign,
static_cast<SizeT>(Is64Aware ? FLATBUFFERS_MAX_64_BUFFER_SIZE
: FLATBUFFERS_MAX_BUFFER_SIZE)),
num_field_loc(0),
max_voffset_(0),
length_of_64_bit_region_(0),
nested(false),
finished(false),
minalign_(1),
@@ -98,10 +110,13 @@ class FlatBufferBuilder {
}
/// @brief Move constructor for FlatBufferBuilder.
FlatBufferBuilder(FlatBufferBuilder &&other) noexcept
: buf_(1024, nullptr, false, AlignOf<largest_scalar_t>()),
FlatBufferBuilderImpl(FlatBufferBuilderImpl &&other) noexcept
: buf_(1024, nullptr, false, AlignOf<largest_scalar_t>(),
static_cast<SizeT>(Is64Aware ? FLATBUFFERS_MAX_64_BUFFER_SIZE
: FLATBUFFERS_MAX_BUFFER_SIZE)),
num_field_loc(0),
max_voffset_(0),
length_of_64_bit_region_(0),
nested(false),
finished(false),
minalign_(1),
@@ -116,18 +131,19 @@ class FlatBufferBuilder {
}
/// @brief Move assignment operator for FlatBufferBuilder.
FlatBufferBuilder &operator=(FlatBufferBuilder &&other) noexcept {
FlatBufferBuilderImpl &operator=(FlatBufferBuilderImpl &&other) noexcept {
// Move construct a temporary and swap idiom
FlatBufferBuilder temp(std::move(other));
FlatBufferBuilderImpl temp(std::move(other));
Swap(temp);
return *this;
}
void Swap(FlatBufferBuilder &other) {
void Swap(FlatBufferBuilderImpl &other) {
using std::swap;
buf_.swap(other.buf_);
swap(num_field_loc, other.num_field_loc);
swap(max_voffset_, other.max_voffset_);
swap(length_of_64_bit_region_, other.length_of_64_bit_region_);
swap(nested, other.nested);
swap(finished, other.finished);
swap(minalign_, other.minalign_);
@@ -136,7 +152,7 @@ class FlatBufferBuilder {
swap(string_pool, other.string_pool);
}
~FlatBufferBuilder() {
~FlatBufferBuilderImpl() {
if (string_pool) delete string_pool;
}
@@ -153,12 +169,36 @@ class FlatBufferBuilder {
nested = false;
finished = false;
minalign_ = 1;
length_of_64_bit_region_ = 0;
if (string_pool) string_pool->clear();
}
/// @brief The current size of the serialized buffer, counting from the end.
/// @return Returns an `SizeT` with the current size of the buffer.
SizeT GetSize() const { return buf_.size(); }
/// @brief The current size of the serialized buffer relative to the end of
/// the 32-bit region.
/// @return Returns an `uoffset_t` with the current size of the buffer.
uoffset_t GetSize() const { return buf_.size(); }
template<bool is_64 = Is64Aware>
// Only enable this method for the 64-bit builder, as only that builder is
// concerned with the 32/64-bit boundary, and should be the one to bare any
// run time costs.
typename std::enable_if<is_64, uoffset_t>::type GetSizeRelative32BitRegion()
const {
//[32-bit region][64-bit region]
// [XXXXXXXXXXXXXXXXXXX] GetSize()
// [YYYYYYYYYYYYY] length_of_64_bit_region_
// [ZZZZ] return size
return static_cast<uoffset_t>(GetSize() - length_of_64_bit_region_);
}
template<bool is_64 = Is64Aware>
// Only enable this method for the 32-bit builder.
typename std::enable_if<!is_64, uoffset_t>::type GetSizeRelative32BitRegion()
const {
return static_cast<uoffset_t>(GetSize());
}
/// @brief Get the serialized buffer (after you call `Finish()`).
/// @return Returns an `uint8_t` pointer to the FlatBuffer data inside the
@@ -270,14 +310,16 @@ class FlatBufferBuilder {
}
// Write a single aligned scalar to the buffer
template<typename T> uoffset_t PushElement(T element) {
template<typename T, typename ReturnT = uoffset_t>
ReturnT PushElement(T element) {
AssertScalarT<T>();
Align(sizeof(T));
buf_.push_small(EndianScalar(element));
return GetSize();
return CalculateOffset<ReturnT>();
}
template<typename T> uoffset_t PushElement(Offset<T> off) {
template<typename T, template<typename> class OffsetT = Offset>
uoffset_t PushElement(OffsetT<T> off) {
// Special case for offsets: see ReferTo below.
return PushElement(ReferTo(off.o));
}
@@ -307,11 +349,16 @@ class FlatBufferBuilder {
AddElement(field, ReferTo(off.o), static_cast<uoffset_t>(0));
}
template<typename T> void AddOffset(voffset_t field, Offset64<T> off) {
if (off.IsNull()) return; // Don't store.
AddElement(field, ReferTo(off.o), static_cast<uoffset64_t>(0));
}
template<typename T> void AddStruct(voffset_t field, const T *structptr) {
if (!structptr) return; // Default, don't store.
Align(AlignOf<T>());
buf_.push_small(*structptr);
TrackField(field, GetSize());
TrackField(field, CalculateOffset<uoffset_t>());
}
void AddStructOffset(voffset_t field, uoffset_t off) {
@@ -322,12 +369,29 @@ class FlatBufferBuilder {
// This function converts them to be relative to the current location
// in the buffer (when stored here), pointing upwards.
uoffset_t ReferTo(uoffset_t off) {
// Align to ensure GetSize() below is correct.
// Align to ensure GetSizeRelative32BitRegion() below is correct.
Align(sizeof(uoffset_t));
// Offset must refer to something already in buffer.
const uoffset_t size = GetSize();
// 32-bit offsets are relative to the tail of the 32-bit region of the
// buffer. For most cases (without 64-bit entities) this is equivalent to
// size of the whole buffer (e.g. GetSize())
return ReferTo(off, GetSizeRelative32BitRegion());
}
uoffset64_t ReferTo(uoffset64_t off) {
// Align to ensure GetSize() below is correct.
Align(sizeof(uoffset64_t));
// 64-bit offsets are relative to tail of the whole buffer
return ReferTo(off, GetSize());
}
template<typename T, typename T2> T ReferTo(const T off, const T2 size) {
FLATBUFFERS_ASSERT(off && off <= size);
return size - off + static_cast<uoffset_t>(sizeof(uoffset_t));
return size - off + static_cast<T>(sizeof(T));
}
template<typename T> T ReferTo(const T off, const T size) {
FLATBUFFERS_ASSERT(off && off <= size);
return size - off + static_cast<T>(sizeof(T));
}
void NotNested() {
@@ -349,7 +413,7 @@ class FlatBufferBuilder {
uoffset_t StartTable() {
NotNested();
nested = true;
return GetSize();
return GetSizeRelative32BitRegion();
}
// This finishes one serialized object by generating the vtable if it's a
@@ -360,7 +424,9 @@ class FlatBufferBuilder {
FLATBUFFERS_ASSERT(nested);
// Write the vtable offset, which is the start of any Table.
// We fill its value later.
auto vtableoffsetloc = PushElement<soffset_t>(0);
// This is relative to the end of the 32-bit region.
const uoffset_t vtable_offset_loc =
static_cast<uoffset_t>(PushElement<soffset_t>(0));
// Write a vtable, which consists entirely of voffset_t elements.
// It starts with the number of offsets, followed by a type id, followed
// by the offsets themselves. In reverse:
@@ -370,7 +436,7 @@ class FlatBufferBuilder {
(std::max)(static_cast<voffset_t>(max_voffset_ + sizeof(voffset_t)),
FieldIndexToOffset(0));
buf_.fill_big(max_voffset_);
auto table_object_size = vtableoffsetloc - start;
const uoffset_t table_object_size = vtable_offset_loc - start;
// Vtable use 16bit offsets.
FLATBUFFERS_ASSERT(table_object_size < 0x10000);
WriteScalar<voffset_t>(buf_.data() + sizeof(voffset_t),
@@ -380,7 +446,8 @@ class FlatBufferBuilder {
for (auto it = buf_.scratch_end() - num_field_loc * sizeof(FieldLoc);
it < buf_.scratch_end(); it += sizeof(FieldLoc)) {
auto field_location = reinterpret_cast<FieldLoc *>(it);
auto pos = static_cast<voffset_t>(vtableoffsetloc - field_location->off);
const voffset_t pos =
static_cast<voffset_t>(vtable_offset_loc - field_location->off);
// If this asserts, it means you've set a field twice.
FLATBUFFERS_ASSERT(
!ReadScalar<voffset_t>(buf_.data() + field_location->id));
@@ -389,7 +456,7 @@ class FlatBufferBuilder {
ClearOffsets();
auto vt1 = reinterpret_cast<voffset_t *>(buf_.data());
auto vt1_size = ReadScalar<voffset_t>(vt1);
auto vt_use = GetSize();
auto vt_use = GetSizeRelative32BitRegion();
// See if we already have generated a vtable with this exact same
// layout before. If so, make it point to the old one, remove this one.
if (dedup_vtables_) {
@@ -400,23 +467,24 @@ class FlatBufferBuilder {
auto vt2_size = ReadScalar<voffset_t>(vt2);
if (vt1_size != vt2_size || 0 != memcmp(vt2, vt1, vt1_size)) continue;
vt_use = *vt_offset_ptr;
buf_.pop(GetSize() - vtableoffsetloc);
buf_.pop(GetSizeRelative32BitRegion() - vtable_offset_loc);
break;
}
}
// If this is a new vtable, remember it.
if (vt_use == GetSize()) { buf_.scratch_push_small(vt_use); }
if (vt_use == GetSizeRelative32BitRegion()) {
buf_.scratch_push_small(vt_use);
}
// Fill the vtable offset we created above.
// The offset points from the beginning of the object to where the
// vtable is stored.
// The offset points from the beginning of the object to where the vtable is
// stored.
// Offsets default direction is downward in memory for future format
// flexibility (storing all vtables at the start of the file).
WriteScalar(buf_.data_at(vtableoffsetloc),
WriteScalar(buf_.data_at(vtable_offset_loc + length_of_64_bit_region_),
static_cast<soffset_t>(vt_use) -
static_cast<soffset_t>(vtableoffsetloc));
static_cast<soffset_t>(vtable_offset_loc));
nested = false;
return vtableoffsetloc;
return vtable_offset_loc;
}
FLATBUFFERS_ATTRIBUTE([[deprecated("call the version above instead")]])
@@ -426,14 +494,20 @@ class FlatBufferBuilder {
// This checks a required field has been set in a given table that has
// just been constructed.
template<typename T> void Required(Offset<T> table, voffset_t field);
template<typename T> void Required(Offset<T> table, voffset_t field) {
auto table_ptr = reinterpret_cast<const Table *>(buf_.data_at(table.o));
bool ok = table_ptr->GetOptionalFieldOffset(field) != 0;
// If this fails, the caller will show what field needs to be set.
FLATBUFFERS_ASSERT(ok);
(void)ok;
}
uoffset_t StartStruct(size_t alignment) {
Align(alignment);
return GetSize();
return GetSizeRelative32BitRegion();
}
uoffset_t EndStruct() { return GetSize(); }
uoffset_t EndStruct() { return GetSizeRelative32BitRegion(); }
void ClearOffsets() {
buf_.scratch_pop(num_field_loc * sizeof(FieldLoc));
@@ -442,15 +516,18 @@ class FlatBufferBuilder {
}
// Aligns such that when "len" bytes are written, an object can be written
// after it with "alignment" without padding.
// after it (forward in the buffer) with "alignment" without padding.
void PreAlign(size_t len, size_t alignment) {
if (len == 0) return;
TrackMinAlign(alignment);
buf_.fill(PaddingBytes(GetSize() + len, alignment));
}
template<typename T> void PreAlign(size_t len) {
AssertScalarT<T>();
PreAlign(len, AlignOf<T>());
// Aligns such than when "len" bytes are written, an object of type `AlignT`
// can be written after it (forward in the buffer) without padding.
template<typename AlignT> void PreAlign(size_t len) {
AssertScalarT<AlignT>();
PreAlign(len, AlignOf<AlignT>());
}
/// @endcond
@@ -458,34 +535,35 @@ class FlatBufferBuilder {
/// @param[in] str A const char pointer to the data to be stored as a string.
/// @param[in] len The number of bytes that should be stored from `str`.
/// @return Returns the offset in the buffer where the string starts.
Offset<String> CreateString(const char *str, size_t len) {
NotNested();
PreAlign<uoffset_t>(len + 1); // Always 0-terminated.
buf_.fill(1);
PushBytes(reinterpret_cast<const uint8_t *>(str), len);
PushElement(static_cast<uoffset_t>(len));
return Offset<String>(GetSize());
template<template<typename> class OffsetT = Offset>
OffsetT<String> CreateString(const char *str, size_t len) {
CreateStringImpl(str, len);
return OffsetT<String>(
CalculateOffset<typename OffsetT<String>::offset_type>());
}
/// @brief Store a string in the buffer, which is null-terminated.
/// @param[in] str A const char pointer to a C-string to add to the buffer.
/// @return Returns the offset in the buffer where the string starts.
Offset<String> CreateString(const char *str) {
return CreateString(str, strlen(str));
template<template<typename> class OffsetT = Offset>
OffsetT<String> CreateString(const char *str) {
return CreateString<OffsetT>(str, strlen(str));
}
/// @brief Store a string in the buffer, which is null-terminated.
/// @param[in] str A char pointer to a C-string to add to the buffer.
/// @return Returns the offset in the buffer where the string starts.
Offset<String> CreateString(char *str) {
return CreateString(str, strlen(str));
template<template<typename> class OffsetT = Offset>
OffsetT<String> CreateString(char *str) {
return CreateString<OffsetT>(str, strlen(str));
}
/// @brief Store a string in the buffer, which can contain any binary data.
/// @param[in] str A const reference to a std::string to store in the buffer.
/// @return Returns the offset in the buffer where the string starts.
Offset<String> CreateString(const std::string &str) {
return CreateString(str.c_str(), str.length());
template<template<typename> class OffsetT = Offset>
OffsetT<String> CreateString(const std::string &str) {
return CreateString<OffsetT>(str.c_str(), str.length());
}
// clang-format off
@@ -493,8 +571,9 @@ class FlatBufferBuilder {
/// @brief Store a string in the buffer, which can contain any binary data.
/// @param[in] str A const string_view to copy in to the buffer.
/// @return Returns the offset in the buffer where the string starts.
Offset<String> CreateString(flatbuffers::string_view str) {
return CreateString(str.data(), str.size());
template<template <typename> class OffsetT = Offset>
OffsetT<String>CreateString(flatbuffers::string_view str) {
return CreateString<OffsetT>(str.data(), str.size());
}
#endif // FLATBUFFERS_HAS_STRING_VIEW
// clang-format on
@@ -502,16 +581,21 @@ class FlatBufferBuilder {
/// @brief Store a string in the buffer, which can contain any binary data.
/// @param[in] str A const pointer to a `String` struct to add to the buffer.
/// @return Returns the offset in the buffer where the string starts
Offset<String> CreateString(const String *str) {
return str ? CreateString(str->c_str(), str->size()) : 0;
template<template<typename> class OffsetT = Offset>
OffsetT<String> CreateString(const String *str) {
return str ? CreateString<OffsetT>(str->c_str(), str->size()) : 0;
}
/// @brief Store a string in the buffer, which can contain any binary data.
/// @param[in] str A const reference to a std::string like type with support
/// of T::c_str() and T::length() to store in the buffer.
/// @return Returns the offset in the buffer where the string starts.
template<typename T> Offset<String> CreateString(const T &str) {
return CreateString(str.c_str(), str.length());
template<template<typename> class OffsetT = Offset,
// No need to explicitly declare the T type, let the compiler deduce
// it.
int &...ExplicitArgumentBarrier, typename T>
OffsetT<String> CreateString(const T &str) {
return CreateString<OffsetT>(str.c_str(), str.length());
}
/// @brief Store a string in the buffer, which can contain any binary data.
@@ -523,12 +607,14 @@ class FlatBufferBuilder {
/// @return Returns the offset in the buffer where the string starts.
Offset<String> CreateSharedString(const char *str, size_t len) {
FLATBUFFERS_ASSERT(FLATBUFFERS_GENERAL_HEAP_ALLOC_OK);
if (!string_pool)
if (!string_pool) {
string_pool = new StringOffsetMap(StringOffsetCompare(buf_));
auto size_before_string = buf_.size();
}
const size_t size_before_string = buf_.size();
// Must first serialize the string, since the set is all offsets into
// buffer.
auto off = CreateString(str, len);
const Offset<String> off = CreateString<Offset>(str, len);
auto it = string_pool->find(off);
// If it exists we reuse existing serialized data!
if (it != string_pool->end()) {
@@ -584,21 +670,27 @@ class FlatBufferBuilder {
}
/// @cond FLATBUFFERS_INTERNAL
uoffset_t EndVector(size_t len) {
template<typename LenT = uoffset_t, typename ReturnT = uoffset_t>
ReturnT EndVector(size_t len) {
FLATBUFFERS_ASSERT(nested); // Hit if no corresponding StartVector.
nested = false;
return PushElement(static_cast<uoffset_t>(len));
return PushElement<LenT, ReturnT>(static_cast<LenT>(len));
}
template<template<typename> class OffsetT = Offset, typename LenT = uint32_t>
void StartVector(size_t len, size_t elemsize, size_t alignment) {
NotNested();
nested = true;
PreAlign<uoffset_t>(len * elemsize);
// Align to the Length type of the vector (either 32-bit or 64-bit), so
// that the length of the buffer can be added without padding.
PreAlign<LenT>(len * elemsize);
PreAlign(len * elemsize, alignment); // Just in case elemsize > uoffset_t.
}
template<typename T> void StartVector(size_t len) {
return StartVector(len, sizeof(T), AlignOf<T>());
template<typename T, template<typename> class OffsetT = Offset,
typename LenT = uint32_t>
void StartVector(size_t len) {
return StartVector<OffsetT, LenT>(len, sizeof(T), AlignOf<T>());
}
// Call this right before StartVector/CreateVector if you want to force the
@@ -623,31 +715,39 @@ class FlatBufferBuilder {
/// @brief Serialize an array into a FlatBuffer `vector`.
/// @tparam T The data type of the array elements.
/// @tparam OffsetT the type of offset to return
/// @tparam VectorT the type of vector to cast to.
/// @param[in] v A pointer to the array of type `T` to serialize into the
/// buffer as a `vector`.
/// @param[in] len The number of elements to serialize.
/// @return Returns a typed `Offset` into the serialized data indicating
/// @return Returns a typed `TOffset` into the serialized data indicating
/// where the vector is stored.
template<typename T> Offset<Vector<T>> CreateVector(const T *v, size_t len) {
template<typename T, template<typename...> class OffsetT = Offset,
template<typename...> class VectorT = Vector>
OffsetT<VectorT<T>> CreateVector(const T *v, size_t len) {
// The type of the length field in the vector.
typedef typename VectorT<T>::size_type LenT;
typedef typename OffsetT<VectorT<T>>::offset_type offset_type;
// If this assert hits, you're specifying a template argument that is
// causing the wrong overload to be selected, remove it.
AssertScalarT<T>();
StartVector<T>(len);
if (len == 0) { return Offset<Vector<T>>(EndVector(len)); }
// clang-format off
#if FLATBUFFERS_LITTLEENDIAN
PushBytes(reinterpret_cast<const uint8_t *>(v), len * sizeof(T));
#else
if (sizeof(T) == 1) {
PushBytes(reinterpret_cast<const uint8_t *>(v), len);
} else {
for (auto i = len; i > 0; ) {
PushElement(v[--i]);
StartVector<T, OffsetT, LenT>(len);
if (len > 0) {
// clang-format off
#if FLATBUFFERS_LITTLEENDIAN
PushBytes(reinterpret_cast<const uint8_t *>(v), len * sizeof(T));
#else
if (sizeof(T) == 1) {
PushBytes(reinterpret_cast<const uint8_t *>(v), len);
} else {
for (auto i = len; i > 0; ) {
PushElement(v[--i]);
}
}
}
#endif
// clang-format on
return Offset<Vector<T>>(EndVector(len));
#endif
// clang-format on
}
return OffsetT<VectorT<T>>(EndVector<LenT, offset_type>(len));
}
/// @brief Serialize an array like object into a FlatBuffer `vector`.
@@ -689,6 +789,12 @@ class FlatBufferBuilder {
return CreateVector(data(v), v.size());
}
template<template<typename...> class VectorT = Vector64,
int &...ExplicitArgumentBarrier, typename T>
Offset64<VectorT<T>> CreateVector64(const std::vector<T> &v) {
return CreateVector<T, Offset64, VectorT>(data(v), v.size());
}
// vector<bool> may be implemented using a bit-set, so we can't access it as
// an array. Instead, read elements manually.
// Background: https://isocpp.org/blog/2012/11/on-vectorbool
@@ -785,47 +891,19 @@ class FlatBufferBuilder {
/// @param[in] len The number of elements to serialize.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
template<typename T>
Offset<Vector<const T *>> CreateVectorOfStructs(const T *v, size_t len) {
StartVector(len * sizeof(T) / AlignOf<T>(), sizeof(T), AlignOf<T>());
template<typename T, template<typename...> class OffsetT = Offset,
template<typename...> class VectorT = Vector>
OffsetT<VectorT<const T *>> CreateVectorOfStructs(const T *v, size_t len) {
// The type of the length field in the vector.
typedef typename VectorT<T>::size_type LenT;
typedef typename OffsetT<VectorT<const T *>>::offset_type offset_type;
StartVector<OffsetT, LenT>(len * sizeof(T) / AlignOf<T>(), sizeof(T),
AlignOf<T>());
if (len > 0) {
PushBytes(reinterpret_cast<const uint8_t *>(v), sizeof(T) * len);
}
return Offset<Vector<const T *>>(EndVector(len));
}
/// @brief Serialize an array of native structs into a FlatBuffer `vector`.
/// @tparam T The data type of the struct array elements.
/// @tparam S The data type of the native struct array elements.
/// @param[in] v A pointer to the array of type `S` to serialize into the
/// buffer as a `vector`.
/// @param[in] len The number of elements to serialize.
/// @param[in] pack_func Pointer to a function to convert the native struct
/// to the FlatBuffer struct.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
template<typename T, typename S>
Offset<Vector<const T *>> CreateVectorOfNativeStructs(
const S *v, size_t len, T (*const pack_func)(const S &)) {
FLATBUFFERS_ASSERT(pack_func);
auto structs = StartVectorOfStructs<T>(len);
for (size_t i = 0; i < len; i++) { structs[i] = pack_func(v[i]); }
return EndVectorOfStructs<T>(len);
}
/// @brief Serialize an array of native structs into a FlatBuffer `vector`.
/// @tparam T The data type of the struct array elements.
/// @tparam S The data type of the native struct array elements.
/// @param[in] v A pointer to the array of type `S` to serialize into the
/// buffer as a `vector`.
/// @param[in] len The number of elements to serialize.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
template<typename T, typename S>
Offset<Vector<const T *>> CreateVectorOfNativeStructs(const S *v,
size_t len) {
extern T Pack(const S &);
return CreateVectorOfNativeStructs(v, len, Pack);
return OffsetT<VectorT<const T *>>(EndVector<LenT, offset_type>(len));
}
/// @brief Serialize an array of structs into a FlatBuffer `vector`.
@@ -873,10 +951,52 @@ class FlatBufferBuilder {
/// serialize into the buffer as a `vector`.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
template<typename T, typename Alloc = std::allocator<T>>
Offset<Vector<const T *>> CreateVectorOfStructs(
template<typename T, template<typename...> class OffsetT = Offset,
template<typename...> class VectorT = Vector,
typename Alloc = std::allocator<T>>
OffsetT<VectorT<const T *>> CreateVectorOfStructs(
const std::vector<T, Alloc> &v) {
return CreateVectorOfStructs(data(v), v.size());
return CreateVectorOfStructs<T, OffsetT, VectorT>(data(v), v.size());
}
template<template<typename...> class VectorT = Vector64, int &..., typename T>
Offset64<VectorT<const T *>> CreateVectorOfStructs64(
const std::vector<T> &v) {
return CreateVectorOfStructs<T, Offset64, VectorT>(data(v), v.size());
}
/// @brief Serialize an array of native structs into a FlatBuffer `vector`.
/// @tparam T The data type of the struct array elements.
/// @tparam S The data type of the native struct array elements.
/// @param[in] v A pointer to the array of type `S` to serialize into the
/// buffer as a `vector`.
/// @param[in] len The number of elements to serialize.
/// @param[in] pack_func Pointer to a function to convert the native struct
/// to the FlatBuffer struct.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
template<typename T, typename S>
Offset<Vector<const T *>> CreateVectorOfNativeStructs(
const S *v, size_t len, T (*const pack_func)(const S &)) {
FLATBUFFERS_ASSERT(pack_func);
auto structs = StartVectorOfStructs<T>(len);
for (size_t i = 0; i < len; i++) { structs[i] = pack_func(v[i]); }
return EndVectorOfStructs<T>(len);
}
/// @brief Serialize an array of native structs into a FlatBuffer `vector`.
/// @tparam T The data type of the struct array elements.
/// @tparam S The data type of the native struct array elements.
/// @param[in] v A pointer to the array of type `S` to serialize into the
/// buffer as a `vector`.
/// @param[in] len The number of elements to serialize.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
template<typename T, typename S>
Offset<Vector<const T *>> CreateVectorOfNativeStructs(const S *v,
size_t len) {
extern T Pack(const S &);
return CreateVectorOfNativeStructs(v, len, Pack);
}
/// @brief Serialize a `std::vector` of native structs into a FlatBuffer
@@ -979,14 +1099,14 @@ class FlatBufferBuilder {
/// @cond FLATBUFFERS_INTERNAL
template<typename T> struct TableKeyComparator {
TableKeyComparator(vector_downward &buf) : buf_(buf) {}
explicit TableKeyComparator(vector_downward<SizeT> &buf) : buf_(buf) {}
TableKeyComparator(const TableKeyComparator &other) : buf_(other.buf_) {}
bool operator()(const Offset<T> &a, const Offset<T> &b) const {
auto table_a = reinterpret_cast<T *>(buf_.data_at(a.o));
auto table_b = reinterpret_cast<T *>(buf_.data_at(b.o));
return table_a->KeyCompareLessThan(table_b);
}
vector_downward &buf_;
vector_downward<SizeT> &buf_;
private:
FLATBUFFERS_DELETE_FUNC(
@@ -1034,7 +1154,7 @@ class FlatBufferBuilder {
NotNested();
StartVector(len, elemsize, alignment);
buf_.make_space(len * elemsize);
auto vec_start = GetSize();
const uoffset_t vec_start = GetSizeRelative32BitRegion();
auto vec_end = EndVector(len);
*buf = buf_.data_at(vec_start);
return vec_end;
@@ -1085,7 +1205,8 @@ class FlatBufferBuilder {
NotNested();
Align(AlignOf<T>());
buf_.push_small(structobj);
return Offset<const T *>(GetSize());
return Offset<const T *>(
CalculateOffset<typename Offset<const T *>::offset_type>());
}
/// @brief Finish serializing a buffer by writing the root offset.
@@ -1109,7 +1230,7 @@ class FlatBufferBuilder {
Finish(root.o, file_identifier, true);
}
void SwapBufAllocator(FlatBufferBuilder &other) {
void SwapBufAllocator(FlatBufferBuilderImpl &other) {
buf_.swap_allocator(other.buf_);
}
@@ -1119,16 +1240,23 @@ class FlatBufferBuilder {
protected:
// You shouldn't really be copying instances of this class.
FlatBufferBuilder(const FlatBufferBuilder &);
FlatBufferBuilder &operator=(const FlatBufferBuilder &);
FlatBufferBuilderImpl(const FlatBufferBuilderImpl &);
FlatBufferBuilderImpl &operator=(const FlatBufferBuilderImpl &);
void Finish(uoffset_t root, const char *file_identifier, bool size_prefix) {
NotNested();
buf_.clear_scratch();
const size_t prefix_size = size_prefix ? sizeof(SizeT) : 0;
// Make sure we track the alignment of the size prefix.
TrackMinAlign(prefix_size);
const size_t root_offset_size = sizeof(uoffset_t);
const size_t file_id_size = file_identifier ? kFileIdentifierLength : 0;
// This will cause the whole buffer to be aligned.
PreAlign((size_prefix ? sizeof(uoffset_t) : 0) + sizeof(uoffset_t) +
(file_identifier ? kFileIdentifierLength : 0),
minalign_);
PreAlign(prefix_size + root_offset_size + file_id_size, minalign_);
if (file_identifier) {
FLATBUFFERS_ASSERT(strlen(file_identifier) == kFileIdentifierLength);
PushBytes(reinterpret_cast<const uint8_t *>(file_identifier),
@@ -1144,7 +1272,7 @@ class FlatBufferBuilder {
voffset_t id;
};
vector_downward buf_;
vector_downward<SizeT> buf_;
// Accumulating offsets of table members while it is being built.
// We store these in the scratch pad of buf_, after the vtable offsets.
@@ -1153,6 +1281,26 @@ class FlatBufferBuilder {
// possible vtable.
voffset_t max_voffset_;
// This is the length of the 64-bit region of the buffer. The buffer supports
// 64-bit offsets by forcing serialization of those elements in the "tail"
// region of the buffer (i.e. "64-bit region"). To properly keep track of
// offsets that are referenced from the tail of the buffer to not overflow
// their size (e.g. Offset is a uint32_t type), the boundary of the 32-/64-bit
// regions must be tracked.
//
// [ Complete FlatBuffer ]
// [32-bit region][64-bit region]
// ^ ^
// | Tail of the buffer.
// |
// Tail of the 32-bit region of the buffer.
//
// This keeps track of the size of the 64-bit region so that the tail of the
// 32-bit region can be calculated as `GetSize() - length_of_64_bit_region_`.
//
// This will remain 0 if no 64-bit offset types are added to the buffer.
size_t length_of_64_bit_region_;
// Ensure objects are not nested.
bool nested;
@@ -1166,14 +1314,15 @@ class FlatBufferBuilder {
bool dedup_vtables_;
struct StringOffsetCompare {
StringOffsetCompare(const vector_downward &buf) : buf_(&buf) {}
explicit StringOffsetCompare(const vector_downward<SizeT> &buf)
: buf_(&buf) {}
bool operator()(const Offset<String> &a, const Offset<String> &b) const {
auto stra = reinterpret_cast<const String *>(buf_->data_at(a.o));
auto strb = reinterpret_cast<const String *>(buf_->data_at(b.o));
return StringLessThan(stra->data(), stra->size(), strb->data(),
strb->size());
}
const vector_downward *buf_;
const vector_downward<SizeT> *buf_;
};
// For use with CreateSharedString. Instantiated on first use only.
@@ -1181,22 +1330,122 @@ class FlatBufferBuilder {
StringOffsetMap *string_pool;
private:
void CanAddOffset64() {
// If you hit this assertion, you are attempting to add a 64-bit offset to
// a 32-bit only builder. This is because the builder has overloads that
// differ only on the offset size returned: e.g.:
//
// FlatBufferBuilder builder;
// Offset64<String> string_offset = builder.CreateString<Offset64>();
//
// Either use a 64-bit aware builder, or don't try to create an Offset64
// return type.
//
// TODO(derekbailey): we can probably do more enable_if to avoid this
// looking like its possible to the user.
static_assert(Is64Aware, "cannot add 64-bit offset to a 32-bit builder");
// If you hit this assertion, you are attempting to add an 64-bit offset
// item after already serializing a 32-bit item. All 64-bit offsets have to
// added to the tail of the buffer before any 32-bit items can be added.
// Otherwise some items might not be addressable due to the maximum range of
// the 32-bit offset.
FLATBUFFERS_ASSERT(GetSize() == length_of_64_bit_region_);
}
/// @brief Store a string in the buffer, which can contain any binary data.
/// @param[in] str A const char pointer to the data to be stored as a string.
/// @param[in] len The number of bytes that should be stored from `str`.
/// @return Returns the offset in the buffer where the string starts.
void CreateStringImpl(const char *str, size_t len) {
NotNested();
PreAlign<uoffset_t>(len + 1); // Always 0-terminated.
buf_.fill(1);
PushBytes(reinterpret_cast<const uint8_t *>(str), len);
PushElement(static_cast<uoffset_t>(len));
}
// Allocates space for a vector of structures.
// Must be completed with EndVectorOfStructs().
template<typename T> T *StartVectorOfStructs(size_t vector_size) {
StartVector(vector_size * sizeof(T) / AlignOf<T>(), sizeof(T), AlignOf<T>());
template<typename T, template<typename> class OffsetT = Offset>
T *StartVectorOfStructs(size_t vector_size) {
StartVector<OffsetT>(vector_size * sizeof(T) / AlignOf<T>(), sizeof(T),
AlignOf<T>());
return reinterpret_cast<T *>(buf_.make_space(vector_size * sizeof(T)));
}
// End the vector of structures in the flatbuffers.
// Vector should have previously be started with StartVectorOfStructs().
template<typename T, template<typename> class OffsetT = Offset>
OffsetT<Vector<const T *>> EndVectorOfStructs(size_t vector_size) {
return OffsetT<Vector<const T *>>(
EndVector<typename Vector<const T *>::size_type,
typename OffsetT<Vector<const T *>>::offset_type>(
vector_size));
}
template<typename T>
Offset<Vector<const T *>> EndVectorOfStructs(size_t vector_size) {
return Offset<Vector<const T *>>(EndVector(vector_size));
typename std::enable_if<std::is_same<T, uoffset_t>::value, T>::type
CalculateOffset() {
// Default to the end of the 32-bit region. This may or may not be the end
// of the buffer, depending on if any 64-bit offsets have been added.
return GetSizeRelative32BitRegion();
}
// Specializations to handle the 64-bit CalculateOffset, which is relative to
// end of the buffer.
template<typename T>
typename std::enable_if<std::is_same<T, uoffset64_t>::value, T>::type
CalculateOffset() {
// This should never be compiled in when not using a 64-bit builder.
static_assert(Is64Aware, "invalid 64-bit offset in 32-bit builder");
// Store how big the 64-bit region of the buffer is, so we can determine
// where the 32/64 bit boundary is.
length_of_64_bit_region_ = GetSize();
return length_of_64_bit_region_;
}
};
/// @}
// Hack to `FlatBufferBuilder` mean `FlatBufferBuilder<false>` or
// `FlatBufferBuilder<>`, where the template < > syntax is required.
using FlatBufferBuilder = FlatBufferBuilderImpl<false>;
using FlatBufferBuilder64 = FlatBufferBuilderImpl<true>;
// These are external due to GCC not allowing them in the class.
// See: https://stackoverflow.com/q/8061456/868247
template<>
template<>
inline Offset64<String> FlatBufferBuilder64::CreateString(const char *str,
size_t len) {
CanAddOffset64();
CreateStringImpl(str, len);
return Offset64<String>(
CalculateOffset<typename Offset64<String>::offset_type>());
}
// Used to distinguish from real Offsets.
template<typename T = void> struct EmptyOffset {};
// TODO(derekbailey): it would be nice to combine these two methods.
template<>
template<>
inline void FlatBufferBuilder64::StartVector<Offset64, uint32_t>(
size_t len, size_t elemsize, size_t alignment) {
CanAddOffset64();
StartVector<EmptyOffset, uint32_t>(len, elemsize, alignment);
}
template<>
template<>
inline void FlatBufferBuilder64::StartVector<Offset64, uint64_t>(
size_t len, size_t elemsize, size_t alignment) {
CanAddOffset64();
StartVector<EmptyOffset, uint64_t>(len, elemsize, alignment);
}
/// Helpers to get a typed pointer to objects that are currently being built.
/// @warning Creating new objects will lead to reallocations and invalidates
/// the pointer!
@@ -1211,15 +1460,6 @@ const T *GetTemporaryPointer(FlatBufferBuilder &fbb, Offset<T> offset) {
return GetMutableTemporaryPointer<T>(fbb, offset);
}
template<typename T>
void FlatBufferBuilder::Required(Offset<T> table, voffset_t field) {
auto table_ptr = reinterpret_cast<const Table *>(buf_.data_at(table.o));
bool ok = table_ptr->GetOptionalFieldOffset(field) != 0;
// If this fails, the caller will show what field needs to be set.
FLATBUFFERS_ASSERT(ok);
(void)ok;
}
} // namespace flatbuffers
#endif // FLATBUFFERS_VECTOR_DOWNWARD_H_
#endif // FLATBUFFERS_FLATBUFFER_BUILDER_H_

View File

@@ -76,8 +76,20 @@ inline const uint8_t *GetBufferStartFromRootPointer(const void *root) {
}
/// @brief This return the prefixed size of a FlatBuffer.
inline uoffset_t GetPrefixedSize(const uint8_t *buf) {
return ReadScalar<uoffset_t>(buf);
template<typename SizeT = uoffset_t>
inline SizeT GetPrefixedSize(const uint8_t *buf) {
return ReadScalar<SizeT>(buf);
}
// Gets the total length of the buffer given a sized prefixed FlatBuffer.
//
// This includes the size of the prefix as well as the buffer:
//
// [size prefix][flatbuffer]
// |---------length--------|
template<typename SizeT = uoffset_t>
inline SizeT GetSizePrefixedBufferLength(const uint8_t *const buf) {
return ReadScalar<SizeT>(buf) + sizeof(SizeT);
}
// Base class for native objects (FlatBuffer data de-serialized into native

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