Compare commits

...

865 Commits

Author SHA1 Message Date
505ec2fb6a Fix CreateVector/CreateVectorOfStructs for non-std vector types (cpp_vec_type)
When cpp_vec_type is set to a non-std container, Pack methods for scalar,
bool, and plain-struct vectors now use the pointer+size overloads of
CreateVector/CreateVectorOfStructs instead of the std::vector-only overloads.
Extends the combined cpp_vec_type+native_type test to also cover scalar
(ubyte) vectors with a custom container type.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-09 20:48:32 +02:00
19aa2ce420 Fix CreateVectorOfNativeStructs for non-std vector types (cpp_vec_type + native_type)
When a field combines cpp_vec_type (e.g. eastl::vector) with native_type on a
struct, the generated Pack method now uses the pointer+size overload of
CreateVectorOfNativeStructs instead of the std::vector overload, which only
accepts std::vector. Adds a dedicated test covering the combined attribute case.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-09 20:35:36 +02:00
35665b5ae7 Add cpp_vec_type attribute for object API vector customization
Mirrors cpp_str_type and cpp_ptr_type: a per-field cpp_vec_type attribute
lets users substitute any std::vector-compatible container in generated
T-structs, and --cpp-vec-type sets the global default.

NativeVector() resolves the attribute (falling back to the global option,
then std::vector). Changes applied to GenTypeNative, GenMember, GenParam
(CreateDirect), and the CreateVectorOfStrings fast-path guard.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-09 19:55:26 +02:00
9e9f5bbfcf Fix field-level native_type for vector pack and CreateTable args
Complete field-level native_type/native_type_pack_name support in C++
codegen by fixing two remaining locations that only checked struct-level
attributes: vector-of-structs packing and CreateTable argument passing.
Add tests with a struct lacking struct-level native_type to verify
field-level attributes work end-to-end.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-09 15:47:07 +02:00
4edfa03ffc native_type and native_inline on fields 2026-05-09 12:23:35 +02:00
Marcel
03fffb25e2 Set max_compatibility_level=3 for rules_swift (#8920)
This is necessary to be compatible with both rules_swift 2.x and 3.x.
2026-02-05 09:57:00 -08:00
bigjt
1a7495a6dd [C#] Add GetBytes methods for fixed arrays (#8633)
* [C#] Add GetBytes methods for fixed arrays

I wanted to direct access to fixed array bytes. I made some changes to the idl generator to create GetBytes functions following the same naming conventions used for vectors of scalar types. There was not a 'Length' field present to bound the existing index accessor so I added that too.

+ Add generic GetBytes for fixed length arrays of scalar types
+ Implement conditional compilation for ENABLE_SPAN_T:
  - ENABLE_SPAN_T: Returns `Span<T>` using `MemoryMarshal.Cast<byte, T>()` as needed.
  - Else: Returns `ArraySegment<byte>?` for raw byte access
+ Added tests reusing arrays_test.fbs definitions
+ Added const int Length field to support existing index based accessors

* [C#] Sync generated code for after adding GetBytes methods for fixed arrays

---------

Co-authored-by: Björn Harrtell <bjornharrtell@users.noreply.github.com>
2026-02-04 23:13:32 +00:00
Fawdlstty
3c1bb67ae1 sync human-readable value (#8859)
Co-authored-by: Justin Davis <jtdavis777@gmail.com>
2026-02-04 15:43:19 +00:00
Cameron Mulhern
5b9de8b6c0 Fixes Rust code generation for single file output when using namespaces (#8877)
* Adds tests for Rust single file mode

All existing tests only compile Rust code using --rust-module-root-file.

* Adds standalone include tests for Rust

The imports for these tests have been moved to their own file, as the existing intergration_test.rs file hides compilation issues from code generation due to symbols brought into scope outside of the generated code (e.g. `extern crate alloc`).

* Declare alloc crate in every Rust namespace

When performing code generation within a single file, extern crate alloc needs to be delcared to bring alloc into scope within every inner namespace.

* Regenerates generated schemas
2026-02-04 15:28:18 +00:00
Justin Davis
ea0a73d168 disallow circular struct references (#8851)
* detect and fail for circular struct dependencies

* pr comments

* pr comment
2026-02-04 15:15:05 +00:00
souma987
4623cfa4bc Opt in to using experimental Kotlin Native APIs to suppress build warnings (#8885)
- fixes #8846
2026-02-04 14:54:08 +00:00
Peter Shih
9c2c56dc6a Fix typo in comment in idl.h (#8907)
Co-authored-by: Justin Davis <jtdavis777@gmail.com>
2026-02-04 14:12:50 +00:00
brianmacy
429c28c783 fix(rust): Zero vtable memory in write_vtable to prevent uninitialized data (#8898)
The write_vtable() function's comment claimed to "fill the WIP vtable
with zeros" but make_space() only reserves memory without initializing
it. When using custom allocators with non-zeroed buffers, unset vtable
field entries would contain garbage instead of zero (which indicates
"use default value").

This fix explicitly zeros the vtable memory after reserving space,
matching the C++ implementation's buf_.fill_big() behavior.

Added regression test using a garbage-filled allocator (0xAA) that
verifies vtable entries for unset fields are properly zeroed.

Fixes #8894
2026-02-04 09:00:44 -05:00
Markus Junginger
e5a9ff757f flatbuffers.h: fix C++11 compilation (#8857) (#8858)
This constexpr officially works only with C++14 (assignment to lhs, 2 statements) and actually broke some C++11 compilers
2026-02-04 13:34:55 +00:00
Justin Davis
e53732b9b9 Feature: lua now file_ident aware (#8850)
* lua code not file ident aware

* update genned code

* make mac happy

* pr comments
2026-02-04 13:05:08 +00:00
Thiébaud Weksteen
b84b676c89 Fix example of JSON export with flatc (#8892)
Binary files should be placed after "--". Also add a note about missing
file_identifier and --raw-binary.
2026-02-04 07:51:49 -05:00
Iñaki Baz Castillo
3211f857d1 Add --ts-undefined-for-optionals command line option (#8861)
* Add --ts-undefined-for-optionals command line option

# Details

- Fixes #7656
- Added a new `--ts-undefined-for-optionals` command line option for `flatc`.
- If enabled, generated TypeScript code uses `undefined` for optional fields rather than `null`.

* Also add TS generated test files

* Run `sh scripts/clang-format-git.sh`

* also add tests/ts/lalala-options.ts to the repo

* move new tests to tests/ts/optional_values dir

* add tests/ts/optional_values/optional_values_generated.cjs to the repo

* reuse existing optional_scalars.fbs and add new test

* add comma

* sh scripts/clang-format-git.sh

* remove comma

* sh scripts/clang-format-git.sh

* trying things

* sh scripts/clang-format-git.sh

* done

* address feedback

* sh scripts/clang-format-git.sh

* run `sh scripts/clang-format-git.sh`

* remove uneeded `eslint-disable @typescript-eslint/no-namespace` line

---------

Co-authored-by: José Luis Millán <jmillan@aliax.net>
2026-02-04 13:37:41 +01:00
Stefan F.
95ff1f1d80 [c#] Fix Table __vector_as_array correct len calc (#8911)
* fix for https://github.com/google/flatbuffers/issues/8759
__vector_as_array<T> calling ByteBuffer.ToArray<T> with the length in bytes by multiplying len with ByteBuffer.Sizeof<T> and FlatBuffersExampleTests extended to call GetVectorOfLongsArray/GetVectorOfDoublesArray which failed without the fix

* first try to repair build-dotnet-windows

* syntax error fixed

* Update solution creation command in build workflow

add --format sln to the dotnet new command, maybe it is currently creating a .slnx instead?
2026-02-04 13:13:01 +01:00
Jacob Abrams
af8997b567 [Python] Improve python API (#8781)
* Fix generate_code script path

* [Python] Make StartVector public

Make StartVector vector public since it is already being used in
generated code

* [Python] Improve vector creation for Python API

Makes Python API for vectors cleaner like Rust and Swift

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
2026-01-21 01:01:20 +00:00
Derek Bailey
0d67abde45 MODULE.bazel: Upgrade rules_swift version (#8908) 2026-01-20 16:56:11 -08:00
razvanalex
d74e2945f7 [C++] Check for case insensitive keywords (#8420)
* chore(idl): Check for case insensitive keywords

Most languages are not affected by this change. In PHP, some names such
as Bool cannot be used because it is a reserved keyword for to the bool
data type. The field `keywords_casing` in the configs enables checking
all characters in lowercase against every keyword. This should be safe
as flatbuffers does not allow non-ASCII characters in its grammar.

* chore: Fix formatting to follow google's coding style for enums

* chore: Extract convert case to lower when CaseInsensitive

---------

Co-authored-by: Justin Davis <jtdavis777@gmail.com>
Co-authored-by: Derek Bailey <derekbailey@google.com>
2026-01-20 16:06:07 -08:00
Nicolas Ulrich
8914d06ab7 Remove invalid dependency on FLATBUFFERS_GENERATE_HEADERS_SCHEMAS (#8834)
* Remove invalid dependency on FLATBUFFERS_GENERATE_HEADERS_SCHEMAS

add_dependencies() is for targets.

CMake 4.2.0 fails because of this (it shouldn't crash though, but that's another topic). See https://gitlab.kitware.com/cmake/cmake/-/issues/27415

* Use FLATC_TARGET

---------

Co-authored-by: Justin Davis <jtdavis777@gmail.com>
2025-12-22 02:25:14 +00:00
Derek Bailey
522f2379a6 Update CODEOWNERS 2025-12-21 16:10:34 -08:00
Justin Davis
7cb0bcb212 C++ Feature: Mutable union getters (#8852)
* generate mutable union accessors

* add test

* Revert "add test"

This reverts commit 45e352b18f.

* update file

* formatter got in the way

* merge conflicts

* updated genned code

* manually fix code gen bc I can't figure out why this file won't code gen

---------

Co-authored-by: Wouter van Oortmerssen <aardappel@gmail.com>
2025-12-21 17:36:47 -05:00
Justin Davis
b1e7868db6 add verification that type_vec.size == vec.size() (#8853)
Co-authored-by: Wouter van Oortmerssen <aardappel@gmail.com>
2025-12-21 21:55:54 +00:00
Justin Davis
68e3c839c3 update provenance (#8873) 2025-12-21 21:50:57 +00:00
mustiikhalil
0723245085 [Swift] Fixes bazel.build file allowing it to find Vectors folder in 8.5.0 (#8875) 2025-12-21 21:22:49 +00:00
Ville Vesilehto
9d64b9c0c0 fix(go): add bounds checking to ByteVector (#8776)
Add missing bounds checking to ByteVector before slice
operations in the Go FlatBuffers implementation. Relative offset and
vector length are now checked against the buffer size. Instead of
panicking, the code now returns nil. Regression test added.

Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
Co-authored-by: Justin Davis <jtdavis777@gmail.com>
2025-12-21 20:25:30 +00:00
Justin Davis
d01f20f2fb Fix python generation with nested flatbuffers (#8854)
* implement fix from issue

* implement actual fix
2025-12-21 11:18:05 -08:00
Derek Bailey
7e163021e5 FlatBuffers Version 25.12.19 (#8871) 2025-12-19 15:06:07 -08:00
Derek Bailey
57fdd4f995 Default Vector Support C++ (#8870) 2025-12-19 14:32:51 -08:00
Derek Bailey
8cb53ccc95 Add --gen-absl-hash option to generate AbslHashValue for structs. (#8868) 2025-12-19 11:49:50 -08:00
Derek Bailey
fb55e0c9de Run clang-format -i **/*.cpp (#8865) 2025-12-19 10:42:57 -08:00
Derek Bailey
d9fde67eb5 Remove progaurd-rules.pro (#8866) 2025-12-19 09:54:43 -08:00
Derek Bailey
f74fda299d Update CODEOWNERS
Ensure no-one can add to owners other than myself as the official Google representative of this repo.
2025-12-18 17:14:33 -08:00
Derek Bailey
15802fa26c Create CODEOWNERS
Add a CODEOWNERS files to assign ownership to different parts of the code base
2025-12-18 17:03:50 -08:00
souma987
a86afae939 Fix casing in generated Kotlin struct constructor function (#8849)
* fixes #8419
2025-12-14 23:59:17 +00:00
souma987
60910fb7f5 Fix nullability of generated Kotlin ByteBuffer accessors (#8844)
* fixes #8691
2025-12-14 18:56:40 -05:00
Justin Davis
7bfaabc358 [TS] Flexbuffers root vector fix (#8847)
* fix and test

* chatgpt help

* consistent throws in reference.ts
2025-12-14 22:59:27 +01:00
Justin Davis
e1407e4341 Upgrade Kotlin to MacOS 15 (#8845)
* upgrade kotlin and macos

* remove xcode version selection
2025-12-14 13:28:24 -05:00
Justin Davis
c9a301e601 Arrays of Enumerations without a value for 0 are no longer valid (#8836)
* arrays of enums with no value for 0 now throw errors

* move setting key field outside struct check

* set to default instead of required

* unsure of why these bfbs files have changed at this time, checking them in to run the pipelines.

* remove known bad test
2025-12-13 18:40:58 -05:00
James Thompson
19b2300f93 chore: switch package to license expression (#8840)
* switch package to license expression

* Remove license file from package
2025-12-10 09:50:50 -05:00
Justin Davis
e60c0ab9e2 deprecate the two options which have no effect of their own (#8831) 2025-12-08 06:03:11 -05:00
Justin Davis
541dd1a8f5 Fix vector of table with naked ptr (#8830)
* create test that fails to compile

* fix the issue

* add test body

* force commit gneerated header

* build failures

* fix bazel some more
2025-12-07 11:05:54 -08:00
Justin Davis
7711e84919 Fix TS object API generation of schema containing array of enumeration having no zero default (#8832)
* set the array constructor to fill with minvalue

* add regression generation test
2025-12-07 07:35:38 -05:00
Kende Gömöri
89430a14d6 Fix docs: typo & dead link (#8826)
* Fix CHANGELOG.md

* Fix broken doc link
2025-12-05 20:31:04 -05:00
Cameron Mulhern
cfce38ec99 Fixes unused imports in Rust code generator (#8828)
* Fixes unused imports in Rust code generator

* Regenerates generated schemas
2025-12-04 21:59:47 -08:00
Justin Davis
5469bc9ef1 Update flatc.md (#8821) 2025-12-03 14:16:59 +01:00
Ky0toFu
b39f79e5e9 Fix(ts): escape doc comment terminator in generated JSDoc (#8820) 2025-12-03 12:26:13 +00:00
Justin Davis
dc623919bd update docs (#8819)
Fixes #8733
2025-12-03 07:31:49 +01:00
Justin Davis
a1e125af11 Implement --file-names-only (#8788)
* flatc builds and seems to work, some of the extra targets are having linker errors

* fix build system

* pipeline failures

* un-rename files

* refactor to use unique_ptr

* typo

* rm make_unique, add comments

* fix cmake

---------

Co-authored-by: Wouter van Oortmerssen <aardappel@gmail.com>
2025-12-03 04:37:06 +00:00
Richard Patel
0b60686e3d rust: impl TrustedLen for VectorIter (#8797)
Improves unpack performance for vectors by allowing the compiler
to vectorize flatbuffers::Vector to std::vec::Vec conversions,
using the unstable trusted_len feature.

Internally, enables an optimization in src/alloc/vec/spec_extend.rs:
Previously, unpacking a flatbuffers::Vector called
SpecExtend::extend_desugared fallback, which inhibits vectorization
(due to a branch before every element move).  Declaring TrustedLen
allows SpecExtend::extend_trusted, which LLVM can often vectorize
into a memcpy.

For [ubyte] vectors in particular, this turns a rather expensive
loop of 'mov BYTE PTR [rax+r13*1], bpl' into a `call memcpy`.
2025-12-03 04:21:16 +00:00
Fawdlstty
17ceaae16e [rust] add deser support for enum type (#8803)
* add deser support for enum type

* update generated files

* remove deser generator when bitflag enable

* add deser test

* Restore the Rust editions version

* Remove unnecessary modifications
2025-12-02 22:48:45 -05:00
Rob Jellinghaus
a5343d6116 fix(idl_gen_rust): Fix lifetime warning added in Rust 1.89 (#8709)
Rust 1.89 added a new lifetime-related warning:
<https://blog.rust-lang.org/2025/08/07/Rust-1.89.0/#mismatched-lifetime-syntaxes-lint>

The Rust code generator currently emits code which trips this warning. This very small PR
fixes the issue for the relevant generated functions and for the Rust flexbuffers code.

Fixes #8705
2025-12-02 22:27:40 -05:00
Justin Davis
4786322b90 update labeler.yml to v5+ format (#8818) 2025-12-02 21:21:25 -05:00
Cameron Mulhern
646a8bc96a Improves Rust code generation (#8564)
* Fixes checks for serde features in flexbuffers crate

* Removes unused MapReaderIndexer use statement

* Fixes warning about nightly cfg usage

Enabling a cfg attribute through cargo::rustc-cfg in build.rs should be coupled with a cargo::rust-check-cfg value so that the compiler knows about the custom cfg. See: https://doc.rust-lang.org/rustc/check-cfg/cargo-specifics.html#cargorustc-check-cfg-for-buildrsbuild-script.

* Migrates usage of deprecated float constants

This update fixes a compiler warning from use of the old constants.

Constants like EPSILON are now directly on the float primitives (e.g. f32::EPSILON) rather than in the f32 module (std::f32::EPSILON).

The new constants have existed since 1.43.0, which appears to be below the MSRV for the flatbuffers crate.

* Fixes incorrect key in flatbuffers Cargo.toml

The old code was using package.rust, which triggered a warning about an unused key:

warning: flatbuffers/rust/flatbuffers/Cargo.toml: unused manifest key: package.rust

The correct key for specifying MSRV is rust-version. See: https://doc.rust-lang.org/cargo/reference/rust-version.html#rust-version.

---------

Co-authored-by: Wouter van Oortmerssen <aardappel@gmail.com>
2025-12-02 18:06:24 -08:00
Felix
0e3471d6a7 WIP error messages (#8764)
Co-authored-by: Wouter van Oortmerssen <aardappel@gmail.com>
2025-12-02 17:52:30 -08:00
Felix
b07589a0f9 CI: Fix typo in version (#8817) 2025-12-02 16:14:43 -05:00
mustiikhalil
2062c33cd4 Add support for Flexbuffers in wasm (#8815) 2025-12-02 16:18:24 +01:00
Felix
adb7add87e Modernize GitHub CI actions (#8812)
* CI: Modernize actions/checkout

* CI: Modernize actions/stale

* CI: Modernize softprops/action-gh-release

* CI: Modernize microsoft/setup-msbuild

* CI: Modernize gradle/actions/setup-gradle

* CI: Modernize actions/setup-dotnet

* CI: Modernize actions/setup-java

* CI: Modernize jiro4989/setup-nim-action

* CI: Update to latest image seems to be fixed

The readme list swift now for 24.04

* CI: Update to latest actions/labeler tag instead of sha
2025-12-02 10:11:55 -05:00
mustiikhalil
29f99937c4 Migrating to swift wasm on for github actions (#8814)
Migrate to use the native SDK for Wasm that's built for swift
2025-12-02 02:13:22 +01:00
Jacob Abrams
597e76a268 Optimize Offset/Pad/Prep: use cached head and slicing, reduce casting (#8808) 2025-12-01 19:00:20 -05:00
Wakahisa
a577050817 [Java] Use Table's fully qualified path (#8729)
* [Java] Use Table's fully qualified path

When a table's name is called `Table`, the Java bindings generated result in an error due to there being  2 Tables. This fixes the issue by fully qualifyng the flatbuffers Table import.

* Update codegen

* Update generated Java code

---------

Co-authored-by: Neville Dipale <neville@urbanlogiq.com>
2025-12-01 11:28:50 -05:00
razvanalex
31ab0bf6c8 [Go] Write required string fields into the buffer when using Object API (#8402)
* [Go] Write required string fields into the buffer when using Object API

In C++, CreateX allows to write the default "" value of a required
string, when the string is not explicitly set. Object API Pack method
uses this implementation of CreateX.

However, in go, despite whether the field is optional or required, it is
always checked against empty string allowing to create messages that
fail to pass the verifier. This commits partially reverts #7719 when the
string field is required.

* Add test for serializing required string fields using Object API

* Update generated code

The Monster schema contains a key string field. For historical
convenience reasons, string keys are assumed required.
2025-12-01 09:50:03 -05:00
Jeroen Demeyer
e4775aa3fe [Go] add BenchmarkBuildAllocations (#8287) 2025-11-30 22:12:12 -05:00
whiteye
97d26ab4ae fix CScript string.compare (#8547)
* fix CScript string.compare

Because the default compare sorting rules of c# string are different from those of cpp, the binary file exported by flatc -b cannot use LookupByKey

* run generate_code.py

---------
2025-11-30 22:06:41 -05:00
James Robinson
7dd38fa23a Fix platform ifdefs for locale independent str functions (#8678)
Android libraries include <android/api-level.h> which defines the __ANDROID_API__ symbol even when targeting non-Android platforms and not using Android's libc. This updates the FLATBUFFERS_LOCALE_INDEPENDENT ifdef to check for __ANDROID__ before checking the Android API level.

Removes an extra check from the __Fuchsia__ branch. Fuchsia's libc does not support locales or the locale independent entry points.

Updates the Android API check to check for an API level >= 26 instead of 21. This matches the Android header file's availability macros and Bionic documentation:

https://android.googlesource.com/platform/bionic/+/HEAD/docs/status.md
2025-11-30 21:38:37 -05:00
Jacob Abrams
7350c3668f Optimize Builder startup: lazy sharedStrings and fast vtable init (#8807) 2025-11-30 23:33:34 +00:00
Felix
49d2db93a7 [Python] Fix generating __init__.py for invalid path (#8810)
This tried to generate from a directories "MyGame/Sample/"
for a empty path_ in M, MyGame & MyGame/Sample.
Which is incorrect since we want to start with the first
kPathSeparator `/` and not position 1.
2025-11-30 23:30:55 +00:00
Uilian Ries
807b43c0d7 Remove legacy Conan recipe and update documentation (#8712)
* Remove legacy Conan recipe

Signed-off-by: Uilian Ries <uilianries@gmail.com>

* Document how to install flatbuffers with Conan

Signed-off-by: Uilian Ries <uilianries@gmail.com>

---------

Signed-off-by: Uilian Ries <uilianries@gmail.com>
Co-authored-by: Justin Davis <jtdavis777@gmail.com>
2025-11-30 11:35:02 +00:00
peter-soos
4b823b1b98 [Python] Fix inconsistent creator function naming in generated code (#8791) (#8792) 2025-11-29 16:48:53 -05:00
mustiikhalil
4c47f4c11e Revert back to using swift-actions (#8806)
Reverting to swift-actions since they seem to have fixed the issue with GPG keys
2025-11-27 21:56:20 -05:00
coder7695
2b107e20c5 [fuzzer] Adds code generation target. (#8795)
* adds code generation fuzzer target.

* add buffer verification

* add table verification in codegen fuzzer

---------

Co-authored-by: Björn Harrtell <bjornharrtell@users.noreply.github.com>
2025-11-27 15:52:28 +00:00
Jacob Bandes-Storch
84f4b83d3e TypeScript: read vtable entries as uint16 (#8435)
Co-authored-by: Björn Harrtell <bjornharrtell@users.noreply.github.com>
2025-11-27 10:55:34 +00:00
dependabot[bot]
185e41fac4 Bump js-yaml in the npm_and_yarn group across 1 directory (#8779)
Bumps the npm_and_yarn group with 1 update in the / directory: [js-yaml](https://github.com/nodeca/js-yaml).


Updates `js-yaml` from 4.1.0 to 4.1.1
- [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md)
- [Commits](https://github.com/nodeca/js-yaml/compare/4.1.0...4.1.1)

---
updated-dependencies:
- dependency-name: js-yaml
  dependency-version: 4.1.1
  dependency-type: indirect
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Björn Harrtell <bjornharrtell@users.noreply.github.com>
2025-11-27 11:50:31 +01:00
Grzegorz Owsiany
8b02fe6178 [C++] Fix vtable deduplication for 64-bit buffers >2GB (#8591)
Fixes #8590
2025-11-26 21:12:24 -05:00
Sutou Kouhei
6e0dad8c5f Use macos-15-intel not macos-latest-large for Intel macOS (#8777)
We can't use macos-latest-large in non paid GitHub account but we can
use macos-15-intel in public repositories. If we use macos-15-intel,
we can run CI jobs for Intel macOS in fork repositories.
2025-11-26 19:31:24 -05:00
obones
e3e355d498 feat: library definition for PlatformIO (#8261)
* feat: library definition for PlatformIO

* Update library.json version with release.sh

---------

Co-authored-by: Flávio Zanoni <flaviozg888@gmail.com>
2025-11-26 19:18:13 -05:00
Jakob Kordež
8e901ce17c Fix dart object api test (#8751) 2025-11-26 17:36:08 -05:00
Yuanyuan Chen
7808ae5c88 More robust <span> check (#8631) 2025-11-26 17:33:06 -05:00
Wakahisa
20068cfa05 [Java] Add notify to Java keywords (#8724)
Fixes #8723

Co-authored-by: Neville Dipale <neville@urbanlogiq.com>
Co-authored-by: Max Burke <max@urbanlogiq.com>
2025-11-26 07:59:18 -08:00
Wakahisa
afd07bdec5 [Java] Generate Longs from uint enums (#8727)
Co-authored-by: Neville Dipale <neville@urbanlogiq.com>
Co-authored-by: Max Burke <max@urbanlogiq.com>
2025-11-26 07:58:25 -08:00
Hjalti Leifsson
2951d5383a chore: fix quick start typos (#8520)
* chore: fix another typo

* chore: undo overzealous IDE changes
2025-11-25 16:24:23 -05:00
Glenn Fiedler
ba563de877 add assert to fix GCC warning on Ubuntu 24.04 LTS (#8804) 2025-11-25 14:08:51 -05:00
Fawdlstty
46a2f3f2c2 [dart] fix bug which generated wrong code (#8780) 2025-11-24 10:54:43 -05:00
Ivan Dlugos
7675121eab Add Dart changelog entry for v25.9.23 (#8785)
Documents changes included in the Dart package v25.9.23 release,
which was published to pub.dev.
2025-11-24 09:18:23 -05:00
Benjamin Kietzman
ea2b5148e5 Fix issue #8389: any nonzero byte is truthy (#8690) 2025-11-24 07:26:39 -05:00
Fergus Henderson
20548ff3b6 Size verifier fix 2 (#8740)
* Fixes to make SizeVerifier work.

In particular change all the places in the Flatbuffers library
and generated code that were using `Verifier` to instead use
`VerifierTemplate<TrackBufferSize>` and wrap them all inside
`template <bool TrackBufferSize = false>`.

Also add unit tests for SizeVerifier.

* Format using `sh scripts/clang-format-git.sh`

* Use `B` rather than `TrackBufferSize` for the name of the template parameter.

* Update generated files.
2025-11-24 07:11:32 -05:00
Jacob Abrams
7ea8db05d8 [Python] Add unit test for github issue 8653 (#8786) 2025-11-24 06:41:50 -05:00
Justin Davis
c7b6b66ccb fix: remove a single type hint to retain 2.7.x compatibility (#8799)
Co-authored-by: Hjalti Leifsson <hjaltileifsson@gmail.com>
2025-11-23 12:00:21 -08:00
Justin Davis
ac8b124496 don't crash on a lua file with no root table (#8770)
Co-authored-by: Wouter van Oortmerssen <aardappel@gmail.com>
2025-11-17 22:31:32 +00:00
Justin Davis
88b033b964 add proposed fixes from #8731 (#8771)
Co-authored-by: Wouter van Oortmerssen <aardappel@gmail.com>
2025-11-17 13:46:41 -08:00
Justin Davis
e68355cb22 [C++] Add Vector64 specialization for std::vector<bool> (#8757)
* add vector64 specialization for vector<bool>

* fix generated code

---------

Co-authored-by: Wouter van Oortmerssen <aardappel@gmail.com>
2025-11-17 13:44:28 -08:00
Justin Davis
e3ee24830e Fix Issue #8653 - Python vtables not considering object size (#8683)
* have vtables consider size

* simplification from comment

---------

Co-authored-by: Wouter van Oortmerssen <aardappel@gmail.com>
2025-11-17 13:43:28 -08:00
Felix
2a8f4568e0 Replace usage of make_unique with unique_ptr for cpp11 (#8763) 2025-11-17 13:42:06 -08:00
mustiikhalil
cbf0850828 [Swift] Inline arrays (#8755)
Implements InlineArrays which allow us to use Flatbuffers arrays within
Structs natively, and also implements FlatbufferVectors as a secondary API
when using mutable Structs

Fixes mutations within fixed sizes arrays

Adds tests and remove inout and mutating from generated objects in favor of borrowing

---------

Co-authored-by: Wouter van Oortmerssen <aardappel@gmail.com>
2025-11-15 00:33:16 +01:00
mustiikhalil
7150dfb5c4 [Swift] Bump minimum supported version of swift to 5.10 (#8758) 2025-11-14 15:07:49 -08:00
mustiikhalil
fa87eccd1a Update swift supported features (#8769) 2025-11-14 15:07:25 -08:00
mustiikhalil
a62f45fed8 Improves the performance of the string imp (#8772)
Improves the performance of the implementation in Swift
by using withCString instead of the contigiousString
2025-11-14 15:06:52 -08:00
cosmith-nvidia
599847236c Support native_type for tables when using the C++ object API. (#8668)
* Support native_type for tables when using the C++ object API.

If native_type is specified on a table:
- No object API struct type is generated.
- The object API refers to the table by its native_type.
- UnPack and Create<TableName> methods are declared but not defined; as they
  must be user-provided.

* Add tests for native_type on tables.

* Add documentation for native_type on tables.
2025-11-05 07:50:10 -08:00
cosmith-nvidia
4173b84d4b Fix --gen-compare to not generate comparators for native types. (#8681)
Per the definition of --gen-compare: only generate comparators for object API
generated structs. Types annoated with native_type must define their own
comparators if `--gen-compare` is enabled.

Also enables --gen-compare for native_type_test and fixes the test by adding a
comparator for the Native::Vector3D type.
2025-11-05 00:43:00 +00:00
mustiikhalil
5fe90a9160 [Swift] Implements FlatbuffersVector which confirms to RandomAccessCollection (#8752)
* Implements FlatbuffersVector in swift

Implements FlatbuffersVector which confirms to RandomAccessCollection,
this would give us semi-native sugary syntax to all the arrays in swift port.

This work will also be the foundation of using arrays in swift

* Fix failing tests for Swift
2025-11-04 23:53:59 +00:00
cosmith-nvidia
78a3d59a65 Swap the dependency of CreateX and X::Pack object API functions. (#8754)
Previously: X::Pack forwarded to CreateX.

Now: CreateX will forward to X::Pack.

This is a step toward enabling using native types for tables when using the
object API. When defining a native table, the user will be able to define a
custom X::Pack method (which is more consistent with the existing native_type
functionality for structs). By reversing the order of the dependencies, CreateX
can continue to be auto-generated and will use the custom X::Pack method when
overriden for native_type tables.
2025-11-04 15:42:16 -08:00
are-you-tilted-already
5ed02dc04a Prevent make_span from working with vectors and arrays of pointers (#8735)
* Prevent `make_span` from working with vectors and arrays of pointers

* support `make_structs_span` for little-endian

* fix build: add the required parentheses

---------

Co-authored-by: Wouter van Oortmerssen <aardappel@gmail.com>
2025-11-04 13:47:44 -08:00
Jakob Kordež
592dc50037 Refactor lazy list unpacking (#8746)
Co-authored-by: Wouter van Oortmerssen <aardappel@gmail.com>
2025-10-31 13:41:59 -07:00
coder7695
dd77af75b7 Add conditional check (#8736)
* resolve windows compile error

* add conditional for undef new

---------

Co-authored-by: Wouter van Oortmerssen <aardappel@gmail.com>
2025-10-31 11:20:18 -07:00
Jakob Kordež
051604aeb5 Fix struct vector ordering in pack function (#8747) 2025-10-31 09:59:01 -07:00
Jakob Kordež
4b09586652 Fix union unpacking (#8748) 2025-10-31 09:58:30 -07:00
David Sanderson
4c0eecd25a treat npm_typescript as a dev dependency (#8719)
Treat flatbuffers' definition of npm_typescript as a dev dependency, in order to avoid conflicts when consuming flatbuffers in a repo that also depends on aspect_rules_ts.
2025-10-30 07:49:54 -07:00
mustiikhalil
de25052c72 Fixes failing tests on macOS due to file loading (#8742)
Fixes failing tests due to the usage of URL(fileURLWithPath:isDirectory:) instead of URL(string:)
2025-10-29 11:36:47 -07:00
vsmcea
95053e6a47 Correct span and non-span versions of ToArray() and ToArrayPadded() methods (#8734)
* Correction of bug inside ToArray<T> methods

Avoid allocating too large buffers (len is expressed in bytes, not in Ts).
Added validation to ensure len is a multiple of SizeOf<T>() before converting to array.

* Update ByteBuffer.cs

* Refactor ToArray and ToArrayPadded methods

I understand from failed test that pos, len, padLeft and padRight are expressed in Ts

* Refactor ToArray and ToArrayPadded methods

* Final correction
All functions parameters expressed in bytes for homogeneity
Tests run:
  - UNSAFE_BYTEBUFFER=true/ENABLE_SPAN_T=true: passed
  - UNSAFE_BYTEBUFFER=true/ENABLE_SPAN_T=false: passed
  - UNSAFE_BYTEBUFFER=false/ENABLE_SPAN_T=false: passed
  - UNSAFE_BYTEBUFFER=false/ENABLE_SPAN_T=true: configuration forbidden by compilation
Correction of FlatBuffers.Test.csproj to allow UNSAFE_BYTEBUFFER/ENABLE_SPAN_T tests
Correction of FlatBuffersExampleTests.cs: I think the test was not run because it could not pass (to be reviewed carefully)
2025-10-25 11:58:05 -07:00
Daniel Nguyen
27325e002a docs: clean up whitespace and fix typo in tutorial.md (#8695)
* docs: remove trailing whitespace

* docs: fix typo in tutorial.md
2025-09-25 09:02:22 -07:00
Derek Bailey
1872409707 FlatBuffers Version 25.9.23 (#8708) 2025-09-23 22:18:02 -07:00
dependabot[bot]
c427e1a65d Bump the npm_and_yarn group across 1 directory with 2 updates (#8704)
Bumps the npm_and_yarn group with 2 updates in the / directory: [@eslint/plugin-kit](https://github.com/eslint/rewrite/tree/HEAD/packages/plugin-kit) and [brace-expansion](https://github.com/juliangruber/brace-expansion).


Updates `@eslint/plugin-kit` from 0.3.2 to 0.3.5
- [Release notes](https://github.com/eslint/rewrite/releases)
- [Changelog](https://github.com/eslint/rewrite/blob/main/packages/plugin-kit/CHANGELOG.md)
- [Commits](https://github.com/eslint/rewrite/commits/plugin-kit-v0.3.5/packages/plugin-kit)

Updates `brace-expansion` from 1.1.11 to 1.1.12
- [Release notes](https://github.com/juliangruber/brace-expansion/releases)
- [Commits](https://github.com/juliangruber/brace-expansion/compare/1.1.11...v1.1.12)

---
updated-dependencies:
- dependency-name: "@eslint/plugin-kit"
  dependency-version: 0.3.5
  dependency-type: indirect
  dependency-group: npm_and_yarn
- dependency-name: brace-expansion
  dependency-version: 1.1.12
  dependency-type: indirect
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Derek Bailey <derekbailey@google.com>
2025-09-23 21:54:56 -07:00
Derek Bailey
caf3b494db bulk code format fix (#8707) 2025-09-23 21:50:27 -07:00
Derek Bailey
0e047869da Use the Google Style for clang-format without exceptions (#8706)
This reduces the friction when merging from github and google repos by
using the exact same clang style guide.

MARKDOWN=true
2025-09-23 21:19:33 -07:00
mustiikhalil
881eaab706 Revert back to use the latest from the swiftly ci (#8702) 2025-09-21 21:47:05 -07:00
nurbo
48eccb83db fix(idl_gen_ts): bool to number conversion in mutable API (#8677)
Co-authored-by: Björn Harrtell <bjornharrtell@users.noreply.github.com>
2025-09-11 08:36:15 -07:00
Peter Petrov
3c0511fa6a [C#] Added ToSizedArrayPadded(int padLeft, int padRight) to ByteBuffers to avoid unnecessary copying. (#8658)
* Added ToSizedArrayPadded(int padLeft, int padRight) + ToArrayPadded(pos, len, padLeft, padRight) to the byteBuffers.
This is for API completion and to avoid unnecessary copy when framing my packets. I needed this to create a flat buffer with space in front of it for header / metadata.

* Fix indentation

---------

Co-authored-by: Björn Harrtell <bjornharrtell@users.noreply.github.com>
Co-authored-by: Wouter van Oortmerssen <aardappel@gmail.com>
2025-09-09 11:38:15 -07:00
bigjt
82396fa0fe [C#] Improve Span<> utilization (#8588)
There are a couple instances where the ByteBuffer's Span property was accessed in a loop.
 + Extracted the use of the property outside of the loop to save a few cpu cycles.

Access to the allocator's internal buffer isn't exposed as a ReadOnlySpan<byte> from the ByteBuffer
or the FlatBufferBuilder.
 + Added a few convenience functions to access the buffer using a ReadOnlySpan<byte>.

There are a few cases where built in Span extensions can be used to run optimized code.
 + Added the use of Span.Fill() and ReadOnlySpan.SequenceCompareTo to replace existing loops.

Co-authored-by: Björn Harrtell <bjornharrtell@users.noreply.github.com>
Co-authored-by: Wouter van Oortmerssen <aardappel@gmail.com>
2025-08-28 16:06:18 -07:00
Curt Hagenlocher
a6b337f803 Add bounds checking to a method where it was missing (#8673)
Co-authored-by: Björn Harrtell <bjornharrtell@users.noreply.github.com>
Co-authored-by: Wouter van Oortmerssen <aardappel@gmail.com>
2025-08-28 16:06:03 -07:00
TorsteinTenstadNorsonic
35230bd70c [C#] Fix union verifier (#8593)
* [C#] Add test verifying unions

* [C#] Fix verifying unions

---------

Co-authored-by: Björn Harrtell <bjornharrtell@users.noreply.github.com>
Co-authored-by: Wouter van Oortmerssen <aardappel@gmail.com>
2025-08-28 16:05:42 -07:00
Shashank
deb3d93454 gRPC callbackService support added (#8666)
* grpc callbackService support added

Signed-off-by: shankeleven <shashanksati11@gmail.com>

* tests: regenerate C++ gRPC golden with --grpc-callback-api (CallbackService & async_ reactor APIs); update formatting and method placement

---------

Signed-off-by: shankeleven <shashanksati11@gmail.com>
Co-authored-by: Wouter van Oortmerssen <aardappel@gmail.com>
2025-08-28 15:49:27 -07:00
Felix
b87d04af8c Bugfix: grpc supress incorrect warning (#8669)
new_p is a local addr but is owned now by slice_
thus the life time does not end at the end of the function

Co-authored-by: Wouter van Oortmerssen <aardappel@gmail.com>
2025-08-28 14:27:31 -07:00
Ville Vesilehto
1e6c851dba fix(go/grpc): avoid panic on short FlatBuffers input (#8684)
* fix(go/grpc): avoid panic on short FlatBuffers input

The gRPC codec read the root UOffsetT without checking input size. On
buffers shorter than SizeUOffsetT, GetUint32 touched data[3] and the
process panics.

Add a simple length check and validate the root offset stays within the
buffer. Return clear errors (insufficient data / invalid root offset)
instead of panicking.

Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>

* fix(go/grpc): avoid signed overflow in offset

Keep the bounds check in the unsigned domain (UOffsetT) to avoid
signedness pitfalls.

Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>

* chore: clarify comment regarding offset

A full FlatBuffer structure would be:

- uoffset_t: root table offset (4 bytes)
- soffset_t: vtable offset in root table (4 bytes)
- uint16_t: vtable size (2 bytes)
- uint16_t: table size (2 bytes)

In total 12 bytes. We are only validating the data length
before trying to read the uoffset_t, not the full structure.

Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>

---------

Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
Co-authored-by: Derek Bailey <derekbailey@google.com>
2025-08-28 00:31:57 -07:00
mustiikhalil
6164edf558 Fixes swift windows CI (#8685)
Fixes ci failing to a missing component on the github actions side, and
this is enabled until its fixed from the swiftlylab side

Enables swift ci
2025-08-27 23:49:50 -07:00
Derek Bailey
ef1030ff0b Update build.yml - disable gradle CI failures
Both of this are failing and blocking other non-related PRs, disabling for now.
2025-08-27 23:22:12 -07:00
Derek Bailey
53c8c2ef16 Update build.yml - disable Test Swift Windows
This continually fails and the error message is cryptic enough that I don't know how to fix it without an expert.
2025-08-27 23:11:24 -07:00
Derek Bailey
f83525fe67 Update build.yml - update gradle actions
This follows the recommendation here: https://github.com/gradle/actions/blob/main/docs/setup-gradle.md#general-usage
2025-08-27 22:55:17 -07:00
Derek Bailey
b2cce474ba Update build.yml - use java-version 21
Our CI is broken and this is the error:

```
FAILURE: Build failed with an exception.

* What went wrong:
Gradle requires JVM 17 or later to run. Your build is currently configured to use JVM 11.
```

So updating our java-versions to the latest stable version which is 21 apparently.
2025-08-27 22:41:07 -07:00
Jason
067bfdbde9 Update ts codegen (#8421)
Makes the return type of `static getFullyQualifiedName()` be a string literal instead of just the string type

Update tests

Co-authored-by: Björn Harrtell <bjornharrtell@users.noreply.github.com>
2025-08-17 20:19:08 -07:00
Justin Davis
5218e29aa4 Fix: Actually call ValidateOptions (#8665)
* fix: actually call ValidateOptions

* convert error to warning in validateoptions
2025-08-12 15:30:35 -07:00
vzjc
957e09d684 CMakeLists: include(CheckSymbolExists) so check_symbol_exists() will work (#8580)
CMake 3.6 and earlier included this implicitly. Newer versions require
it to be explicit.

Co-authored-by: Wouter van Oortmerssen <aardappel@gmail.com>
2025-08-11 23:11:14 -07:00
Chan Wang
af4b99a1d7 Add Rust reflection documentation (#8536)
* Add Rust reflection documentation

* Update rust.md
2025-08-08 10:18:17 -07:00
Isaiah Pettingill
b85b90e346 Fix typo in word JavaScript (#8530)
Noticed this on the site. I'm not sure if you have to change it anywhere else, but this looks like the only place the typo occurs
2025-08-08 10:16:52 -07:00
Nugine
ae3821233c docs: fix broken link in readme (#8656) 2025-08-06 22:06:44 -07:00
Felix
ff9cba2bff Doc fix verifier example code for cpp (#8664) 2025-08-06 13:53:44 -07:00
Felix
1759061908 Remove stray required in docs (#8663) 2025-08-06 13:52:57 -07:00
Sourya Kovvali
34af7fff70 Fix native_type non-native_inline fields, add tests (#8655)
* Fix native_type non-native_inline fields, add tests

* Format

* Add 'native_type_test' and 'native_inline_table_test' to generate_code.py

* Remove '--gen-compare' from native_type_test generation
2025-08-03 15:06:01 -07:00
mustiikhalil
518bf42df8 Fixes misaligned pointer by reading from the buffer instead of loading the memory separately (#8649) 2025-07-29 21:26:30 +00:00
mustiikhalil
575d616e60 [Swift] Moves capacity outside of Storage (#8650)
- Cleans up capacity usage within the lib and moves it outside of the Storage

-  Use overflow operators
2025-07-29 14:21:20 -07:00
Felix
f32a7dcbd2 Bugfix __eq__ for numpy data types (#8646)
* [Python] Sync PythonTest.sh flags with generate_code.py

* [Python] Update generated code to latest flatc version for tests

* [Python] Fix test support for numpy newer than 2.0.0

* [Python] Remove unused variable

* [Python] Fix __eq__ for numpy arrays

* [Python] Run clang-format over the entire file
2025-07-26 10:31:38 -07:00
Alex Băluț
860d645349 Support Rust edition 2024 (#8638)
* Developers intro how to contribute

* Fix Rust code generation for Rust edition 2024

The errors look like:

```
warning[E0133]: call to unsafe function `fbs::flatbuffers::emplace_scalar` is unsafe and requires unsafe block
warning[E0133]: call to unsafe function `fbs::flatbuffers::follow_cast_ref` is unsafe and requires unsafe block
warning[E0133]: call to unsafe function `fbs::flatbuffers::Follow::follow` is unsafe and requires unsafe block
warning[E0133]: call to unsafe function `fbs::flatbuffers::read_scalar_at` is unsafe and requires unsafe block
warning[E0133]: call to unsafe function `fbs::flatbuffers::root_unchecked` is unsafe and requires unsafe block
warning[E0133]: call to unsafe function `fbs::flatbuffers::size_prefixed_root_unchecked` is unsafe and requires unsafe block
warning[E0133]: call to unsafe function `fbs::flatbuffers::Table::<'a>::new` is unsafe and requires unsafe block
warning[E0133]: call to unsafe function `std::slice::from_raw_parts` is unsafe and requires unsafe block
```

* Update goldens

Ran `goldens/generate_goldens.py`

* Regenerate code files

Ran `scripts/generate_code.py`
2025-07-25 23:12:52 +00:00
Felix
06a53df0d3 Fix start page: Backwards and Forwards Compatibility (#8645) 2025-07-25 16:06:50 -07:00
Łukasz Kurowski
c526cb640b [Python] Enhance object API __init__ with typed keyword arguments (#8615)
This commit significantly improves the developer experience for the Python Object-Based API by overhauling the generated `__init__` method for `T`-suffixed classes.

Previously, `T` objects had to be instantiated with an empty constructor, and their fields had to be populated manually one by one. This was verbose and not idiomatic Python.

This change modifies the Python code generator (`GenInitialize`) to produce `__init__` methods that are:

1.  **Keyword-Argument-Friendly**: The constructor now accepts all table/struct fields as keyword arguments, allowing for concise, single-line object creation.

2.  **Fully Typed**: The signature of the `__init__` method is now annotated with Python type hints. This provides immediate benefits for static analysis tools (like Mypy) and IDEs, enabling better autocompletion and type checking.

3.  **Correctly Optional**: The generator now correctly wraps types in `Optional[...]` if their default value is `None`. This applies to strings, vectors, and other nullable fields, ensuring strict type safety.

The new approach remains **fully backward-compatible**, as all arguments have default values. Existing code that uses the empty constructor will continue to work without modification.

#### Example of a Generated `__init__`

**Before:**

```python
class KeyValueT(object):
    def __init__(self):
        self.key = None  # type: str
        self.value = None  # type: str
```

**After:**

```python
class KeyValueT(object):
    def __init__(self, key: Optional[str] = None, value: Optional[str] = None):
        self.key = key
        self.value = value
```

#### Example of User Code

**Before:**

```python
# Old, verbose way
kv = KeyValueT()
kv.key = "instrument"
kv.value = "EUR/USD"
```

**After:**

```python
# New, Pythonic way
kv = KeyValueT(key="instrument", value="EUR/USD")
```
2025-07-22 23:57:39 -07:00
mustiikhalil
ca73ff34b7 [Swift] Memory usage fix (#8643)
Allows a complete reset for the underlying memory of the
_InternalByteBuffers within FlatBuffers and FlexBuffers.
2025-07-18 09:37:58 -07:00
Rogério Lino
2e49b3ba60 docs: Fixing typo on PHP sample (#8566) 2025-07-17 19:42:14 +00:00
Felix
f830c47d68 [Python] Avoid double flatbuffers include in pyi files (#8626) 2025-07-17 12:37:19 -07:00
Emma
501810f4d1 Fix JavaScript typo in mkdocs.yml (#8515) 2025-07-17 17:53:12 +00:00
Felix
1047d7ec13 Fix Enum type definition (#8624)
Using the : syntax leads to non member attributes.

> If an attribute is defined in the class body with a type annotation
> but with no assigned value, a type checker should assume this is a non-member attribute

```
class Pet(Enum):
    genus: str  # Non-member attribute
    species: str  # Non-member attribute

    CAT = 1  # Member attribute
    DOG = 2  # Member attribute
```

https://typing.python.org/en/latest/spec/enums.html#defining-members
2025-07-16 12:22:45 -07:00
mustiikhalil
07c2eb5fe7 Moves away from @_exported import to add the import in the generated code (#8637) 2025-07-16 12:07:08 -07:00
Felix
c7b9dc83f5 [Python] Avoid include own type (#8625)
This prevents the include of the type defined in the pyi,
otherwise this leads to error message like this:
error: Name XYZ already defined (possibly by an import)  [no-redef]
2025-07-15 11:20:09 -07:00
Gio
4c9079e31b Update logo path (#8602) 2025-07-14 16:09:05 -07:00
Felix
64e5252b4e Fix typo in code comment (#8549) 2025-07-07 12:03:14 -07:00
Dylan Gallagher
00c30807ff Fixed typo in quick_start.md (#8592) 2025-07-07 12:02:40 -07:00
Felix
c15fe421ba Use correct default type for str (#8623)
* [Python] Use correct type for str with None

Otherwise mypy will correctly flag code like this

def __init__(self):
  self.fooBar = None  # type: Optional[str]

error: Incompatible types in assignment (expression has type "None", variable has type "str")

* [Python] Make list type optional as they can contain None
2025-07-04 23:47:36 +00:00
Felix
6b251aa1cf Bugfix/new decode flag (#8634)
* Add docs for new python-decode-obj-api-strings flag

* Fix generate_code by adding missing s to flag
2025-07-04 16:46:28 -07:00
mustiikhalil
6fe8afb3b6 [CI] Moves swift actions to use next (#8632)
* Moves to use swift-actions@next until final release is out

* Migrates to vapor that uses swiftly actions

* Trying to use windows 2022
2025-07-01 13:46:06 -07:00
Truman Mulholland
00eec2445b [TS] Fix relative paths for exports (#8517)
Fixes an issue where exports were using incorrect relative paths for
>=3 namespace levels. This is fixed by making the starting range of the
namespace components relative to the amount of components.

Co-authored-by: Björn Harrtell <bjornharrtell@users.noreply.github.com>
2025-07-01 08:38:02 -07:00
mustiikhalil
b8db3a9a6a Adds windows swift support (#8622)
Adding support for windows requires the code generations
to add a compiler statement to completely ignore GRPC code
generation on windows

Cleanup the project to use the main Package.swift to run tests
instead of having it separate and includes the imports for GRPC
within it.

Adds windows swift ci
2025-06-30 05:45:48 -07:00
Seth Raymond
75556437cc Decode bytes to strings in Python Object API (#8551) 2025-06-29 01:40:10 -07:00
Felix
31beb0fb2f Bugfix: grpc python code generation location and file suffix (#8359)
* clang-format

* [Python] Replace . with _ in grpc filename suffix

Having filenames with . like `file.fb.grcp`
is not great for Python. Since dots are used for namespaces.
Replacing all of them with _ eg suffix `foo.bar.baz` will become
`foo_bar_baz`.

Restoring the previous default `_fb` suffix.

* [Python] Use namespace in path

This fixes a regression introduced with:
fb9afbafc7
And generates the grpc file in the namespace folder again.

* Sync commandline docs with web docs
2025-06-24 22:52:40 -07:00
Aaron Barany
dfd92124aa Avoid outputting Python files for already generated types (#8500)
This may overwrite types that have already been generated and can create
unwanted empty files. Fixes #8490
2025-06-23 12:00:37 -07:00
Björn Harrtell
a2916d37e7 [TS] Upgrade deps (#8620) 2025-06-22 08:59:42 -07:00
mustiikhalil
5a95b7b6bc [Swift] Flexbuffers native swift port (#8577)
* Offical Swift port for FlexBuffers

This is the offical port for FlexBuffers within
swift, and it introcudes a Common Module where code
is shared between flatbuffers and flexbuffers.

Writing most supported values like maps, vectors,
nil and scalars into a flexbuffer buffer. And includes
tests to verify that its similar to cpp

* Reading a flexbuffer

Implementing reading from a flexbuffer, enabling
most of the buffers features, like most types, maps, vectors,
typedvectors, and fixedtypedvectors.

Currently, if an offset/object cant be read we default to a swift
nil instead of the default flexbuffers 'null' with all values.

* Fixes bazel breaking due to new project structure

Address warnings within the library

* Adds comment on why we added the code & properly enforce the amout of bytes needed
2025-06-22 08:36:38 +02:00
Björn Harrtell
595ac94a6a [TS] Enum value default null (#8619)
* [TS] Enum value default null

* Re-gen
2025-06-21 22:25:56 -07:00
Adam Oleksy
5822c1c8dd Fix dereference operator of VectorIterator to structures (#8425)
For Vector or Array of structures the dereference operator of an
iterator returns the pointer to the structure. However, IndirectHelper,
which is used in the implementation of this operator, is instantiated
in the way that the IndirectHelper::Read returns structure by value.

This is because, Vector and Array instantiate IndirectHelper with
const T*, but VectorIterator instantiates IndirectHelper with T. There
are three IndirectHelper template definition: first for T, second for
Offset<T> and the last one for const T*. Those have different
IndirectHelper:Read implementations and (more importantly) return type.
This is the reason of mismatch in VectorIterator::operator* between
return type declaration and what was exactly returned.

That is, for Array<T,...> where T is scalar the VectorIterator is
instantiated as VectorIterator<T, T>, dereference operator returns T
and its implementation uses IndirectHelper<T> which Read function
returns T.
When T is not scalar, then VectorIterator is instantiated as
VectorIterator<T, const T *>, dereference operator returns const T * and
its implementation uses IndirectHelper<T> which Read function returns T.

The fix is done as follows:
* implement type trait is_specialization_of_Offset and
 is_specialization_of_Offset64,
* change partial specialization of IndirectHelper with const T * that
 it is instantiated by T and enabled only if T is not scalar and not
 specialization of Offset or Offset64,
* remove type differentiation (due to scalar) from Array..

The above makes the IndirectHelper able to correctly instantiate itself
basing only on T. Thus, the instantiation in VectorIterator correctly
instantiate IndirectHelper::Read function, especially the return type.
2025-05-17 22:01:09 -07:00
Maurice Sotzny
609c72ca1a [C++] Fixes #8446 (#8447)
Fixes access to union members when generating code with options "--cpp-field-case-style upper" and "--gen-object-api"

Co-authored-by: Wouter van Oortmerssen <aardappel@gmail.com>
2025-04-14 08:54:10 -07:00
mustiikhalil
bd1b2d0baf [Swift] Adds new API to reduce memory copying within swift (#8484)
* Adds new API to reduce memory copying within swift

Adds new storage container _InternalByteBuffer which
will be holding the data that will be created within the swift
lib, however reading data will be redirected to ByteBuffer, which
should be able to handle all types of data that swift provide without
the need to copy the data itself. This is due to holding a reference to
the data.

Replaces assumingMemoryBinding with bindMemory which is safer

Adds function that provides access to a UnsafeBufferPointer for
scalars and NativeStructs within swift

Updates docs

Suppress compilation warnings by replacing var with let

Using overflow operators within swift to improve performance

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

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

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

* Rust reflection: drop dependency on stdint crate

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

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

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

* Rust reflection: drop dependency on escape_string crate

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

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

* Rust codegen: add derives on generated bitflags

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

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

* Rust flatbuffers: update bitflags dependency to 2.8

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

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

from_bits_unchecked was replaced with safe from_bits_retain.

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

* Regenerate Rust code after idl change

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

* Regenerate reflection_generated.rs

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

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

* ts/BUILD.bazel: add missing import

Found by Buildifire presubmit:

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

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

* Update expected value in generated_code_debug_prints_correctly test

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

This change adjusts the expected test value.

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

* Fix tests build on Swift 5.8

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

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

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

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

---------

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

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

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

Fixup after a9257b6963.

* Align versions in bazel_respository_test_dir with root

* Update XCode version to 15.2

This is the oldest available version.

* Add WORKSPACE.bzlmod

* Add support for Bazel 7

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

* Align npm_translate_lock attrs

* Remove defs_bzl_filename attr

* Align root_package with pnpm-lock.yaml location

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

Restructure presubmit.yml to support matrix.

* Remove testing Ubuntu 18.04

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

* Add testing in Ubuntu 22.04

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

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

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

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

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

* #Rust Add 'Struct' struct and corresponding getter

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

* #Rust Add setters for scalar fields

* #Rust Add setter for string fields

* #Rust Add getter for Table/Vector fields

* #Rust Add buffer verification

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

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

---------

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

as it's referenced in the note below

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

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

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

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

* Fixed missing generated file version checks

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

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

Improves performance for all arrays and for loops

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

Updates benchmark library

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

* feat: use dart enhanced enums

* generate code

---------

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

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

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

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

* Update grpc version to 1.67.1

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

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

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

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

Bump up version of the gson package.

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

* formatting

---------

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

Bug: none

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

* [Rust] Upgrade num_enum to version 0.7.3

---------

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

Correct the word.

* Update ByteBuffer.swift

Type parameter does not existing, remove it.

* Update ByteBuffer.swift

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

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

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

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

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

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

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

To support this change, the following modifications were made:

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

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

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

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

Updates CI to run with swift 5.8

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

Update bazelci to also accept swift 5.8

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

To support this change, the following modifications were made:

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

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

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

* [Python] Update Bazel build rules.

* [Python] Update Bazel build rules.

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

---------

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

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

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

Update release script to update rust flexbuffers

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

* Fixed indentation

* Update release.yml

Change secret name.

* Update release.yml

remove extra space added in merge

---------

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

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

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

Removes references of swift from the windows pipeline for bazel

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

* Update build.yml

Remove comment that is not relevant any longer.

---------

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

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

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

* Update build.yml

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

* Update build.yml

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

* Update build.yml

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

* Update build.yml

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

* Update build.yml

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

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

This includes:

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

* [Python] Fix various codegen problems.

This includes:

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

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

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

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

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

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

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

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

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

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

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

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

Reproduces #8200

* Overload KeyCompareWithValue to work for string-like objects

This fixes #8200.

* Extra tests

---------

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

* Remove mono usage

* Fix bat name ref

* Up deps

* Up deps

* Reinstate build-windows

* Fix name

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-12-19 14:43:55 -08:00
Derek Bailey
e5fc3b16d8 flatbuffer_builder: Prevent Finish() from being called twice 2023-12-19 18:41:26 +00:00
razvanalex
c0d16995a4 [TS/JS] Create byte vectors (#8185)
* Add createByteVector and use set in createString

* Add test for CreateByteVector

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-12-19 06:42:21 +00:00
Derek Bailey
70c8292c29 Update README.md
Remove Google Groups and Gitter links
2023-12-18 19:39:10 -08:00
razvanalex
d47cd10d77 Add Clear() for python Builder (#8186)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-12-17 22:18:11 -08:00
Derek Bailey
66bd3d7400 WORKSPACE: Run Buildifier 2023-12-18 05:47:56 +00:00
Derek Bailey
0cc1edb3ad WORKSPACE: go back to version that was working 2023-12-18 05:42:30 +00:00
Derek Bailey
57375a9e1c WORKSPACE: fix swift 2023-12-18 05:37:38 +00:00
Derek Bailey
0346535221 presubmit.yml: Explicitly use bazel 6.4.0 2023-12-18 05:33:39 +00:00
Derek Bailey
7d62dcc422 WORKSPACE: include latst build_bazel_rules_swift 2023-12-17 07:19:20 +00:00
Derek Bailey
b3cd878dfe WORKSPACE: remove old swift download 2023-12-17 07:12:14 +00:00
Derek Bailey
09486a9f97 WORKSPACE: update apple and rule_js 2023-12-17 07:07:30 +00:00
Yuriy Chernyshov
dd79eed495 Introduce convenient implicit operator string_view (#8181)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-12-16 22:30:21 -08:00
Derek Bailey
0e1305c8e2 Update label.yml
copy paste issue with last commit
2023-12-16 22:22:07 -08:00
Derek Bailey
88549130e1 Update label.yml
Go to version 4.1.0 as version main has breaking changes.
2023-12-16 22:17:46 -08:00
Björn Harrtell
6dfc59dfcc [TS/JS] Upgrade dependencies (#7996) 2023-12-13 16:57:46 -08:00
Aaron Barany
5ba80c24e0 Fix python type annotation output when not enabled (#7983)
Fixes #7971

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-11-29 09:58:21 -08:00
blindspotbounty
da55ac3a27 copy properties for conformance parser (#8174) 2023-11-26 11:35:58 -08:00
Felix
c6f9e010bb Fix cmake build for old versions (#8173)
Adresses all these issues ->
https://github.com/google/flatbuffers/issues/7994
https://github.com/google/flatbuffers/issues/7979
https://github.com/google/flatbuffers/issues/8049

Fix 7994, Fix 7979, Fix 8049

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-11-22 19:32:02 -05:00
mustiikhalil
94ff188a3e [Swift] Migrating benchmarks to a newer lib. (#8168)
* Adds Nativestructs pointer push into ByteBuffer

Updates benchmarks & cleanup

Adds native struct vector tests

* Address PR comments

* Add more benchmarks

* Some benchmark cleanup

* Return back to 1M structs

* Tweak Structs benchmark

* Moves swift Benchmarks folder from /tests to /benchmarks

---------

Co-authored-by: Joakim Hassila <jocke@ordo.one>
2023-11-22 16:08:55 -08:00
abandy
5a937f1ba1 [Swift] Add allowReadingUnalignedBuffers to most ByteBuffer init methods (#8134) 2023-11-20 22:52:19 +00:00
DoppelDe
e1c3690a2a Fix typo in CMakeLists.txt (#8167)
When building with make, it was failing for me because the target grpctext doesn't exist. I strongly assume this was meant to be grpctest.

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-11-20 10:35:56 -08:00
Taylor Holliday
b08abbbbf6 [Swift] Push contiguous bytes (#8157)
* Add version of push which takes ContiguousBytes

* Ensure overloads aren't ambiguous

* Add version of createVector

* Add version of push which takes ContiguousBytes

* Ensure overloads aren't ambiguous

* Add version of createVector

* Add similar conditional to other use of ContiguousBytes

* Attempt CI fix

* Use memcpy instead of copyMemory

memcpy is faster in tests

* Add testContiguousBytes

* Add benchmarks

* Add version of createVector

* Add benchmarks

* Update push to copy memory

Since we don't care about endianness, we can simply memcpy the array of scalars

* Remove function and benchmarks

Since we don't care about endianness, a FixedWidthInteger version of createVector isn't needed

* Improve naming

* Add doc comment
2023-11-20 17:47:11 +01:00
James Courtney
7d6d99c6be Add absolute file names option to BFBS (#8055)
* Add absolute file names option (#1)

* Use ternary style for if

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-11-19 18:58:03 +00:00
Derek Bailey
d3055a97e7 update goldens with namespace 2023-11-19 07:51:36 +00:00
mustiikhalil
0dc5a75dc0 Update testReadFromOtherLanguages test to also run on macos (#8044) 2023-11-19 07:18:49 +00:00
tira-misu
f175e60998 [GO] compiles to much files (#8118)
* 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

* Generate only files for comiled fbs (not for dependend ones)

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-11-18 19:23:09 -08:00
Derek Bailey
a632c3c004 Update build.yml (#8163)
* Update build.yml

Use our enterprise runners

* Make a default runs-on

* Update build.yml

Use the latest 64-core runners

* Update build.yml

Fix windows runner that don't have visual studios

* Update build.yml

use windows-2019 as the 2022 doesn't seem to have visual studios installed
2023-11-18 15:04:24 -08:00
Aleksandr Smolin
11789e41b6 Add argument to FlatBufferToString for quotes around field names, default false (#8090)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-11-18 21:29:41 +00:00
dependabot[bot]
a9c0845504 Bump word-wrap from 1.2.3 to 1.2.4 (#8042)
Bumps [word-wrap](https://github.com/jonschlinkert/word-wrap) from 1.2.3 to 1.2.4.
- [Release notes](https://github.com/jonschlinkert/word-wrap/releases)
- [Commits](https://github.com/jonschlinkert/word-wrap/compare/1.2.3...1.2.4)

---
updated-dependencies:
- dependency-name: word-wrap
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-11-18 13:23:28 -08:00
mustiikhalil
526c92546f Fixes forward offset verifiable objects within arrays (#8135)
Fixes failing tests & removes XCTestsManifests

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-11-18 21:14:55 +00:00
Derek Bailey
eb80ead90b Update build.yml (#8162)
Removes some old comments from the CI builds.
2023-11-18 13:09:02 -08:00
Artem Shilkin
386b6353ed data() instead of c_str() (#8069) 2023-11-18 12:50:51 -08:00
Peter Dye
d09696bbe6 Fix spelling mistake in FlatBufferBuilder.cs doc comments (#8120)
No change to code. Very simple spelling mistake/typo fix.
2023-11-18 12:14:25 -08:00
Lukas
a228e8c9b8 Add help text to cmake git describe error message (#8123) 2023-11-18 12:13:54 -08:00
dependabot[bot]
91a3172519 Bump google.golang.org/grpc in /grpc/examples/go/greeter/client (#8131)
Bumps [google.golang.org/grpc](https://github.com/grpc/grpc-go) from 1.53.0 to 1.56.3.
- [Release notes](https://github.com/grpc/grpc-go/releases)
- [Commits](https://github.com/grpc/grpc-go/compare/v1.53.0...v1.56.3)

---
updated-dependencies:
- dependency-name: google.golang.org/grpc
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-11-18 12:12:44 -08:00
dependabot[bot]
e0d4562782 Bump google.golang.org/grpc in /grpc/examples/go/greeter/server (#8132)
Bumps [google.golang.org/grpc](https://github.com/grpc/grpc-go) from 1.53.0 to 1.56.3.
- [Release notes](https://github.com/grpc/grpc-go/releases)
- [Commits](https://github.com/grpc/grpc-go/compare/v1.53.0...v1.56.3)

---
updated-dependencies:
- dependency-name: google.golang.org/grpc
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-11-18 12:12:16 -08:00
dependabot[bot]
49677b0b70 Bump google.golang.org/grpc in /grpc/examples/go/greeter/models (#8130)
Bumps [google.golang.org/grpc](https://github.com/grpc/grpc-go) from 1.53.0 to 1.56.3.
- [Release notes](https://github.com/grpc/grpc-go/releases)
- [Commits](https://github.com/grpc/grpc-go/compare/v1.53.0...v1.56.3)

---
updated-dependencies:
- dependency-name: google.golang.org/grpc
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-11-18 12:11:35 -08:00
Lukas
8e34ad5db7 Remove pragma warning disable C4351 as it is undocumented (#8124)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-11-18 12:09:47 -08:00
Felix
eb64390080 Update Compiler.md docs (#8153)
* Escape singel underscores in markdown

* Update language generator flags in docs

* Complet the list of Python options
2023-11-18 12:08:04 -08:00
Gleb Lamm
46577d0d2f Fix: detect c++ standard on MSVC for span (#8155) 2023-11-18 12:06:18 -08:00
Ivan Dlugos
32029ac699 chore: Dart 23.5.26 release (#8160)
* chore: update generated test code

* chore: update changelog

* update sdk constraints

* chore: update readme

* minor linter issues
2023-11-18 11:56:54 -08:00
Derek Bailey
4354945727 Fix CI builds (#8161)
* Update build.yml

Upgrade to gcc 13 and clang 15

* switch to __is_trivially_copyable

* fix cmake issue and warning about sign comparison

* Use libc++ for C++23 on clang for now

* Use libc++ for C++23 on clang for now

* exclude clang+15 for C++13 builds
2023-11-18 00:19:03 -08:00
Steven Toribio
755573bcda wow (#8158) 2023-11-16 10:22:29 -08:00
adsnaider
205285c35c [Rust] Add the Allocator trait for the builder API (#8106)
* Add an Allocator trait for FlatBufferBuilder

* Update rust generated code
2023-10-07 15:28:52 -04:00
Curt Hagenlocher
f4e23bf91e Fix verification for C# unions (#7970)
* Fix verification for unions

* Run scripts\generate_code.py

---------

Co-authored-by: Michael Le <michael.le647@gmail.com>
2023-09-30 18:54:48 -07:00
Lukas
1fdb5d263a Add const qualifier to non-mutated FlatbufferBuilder parameter (#8101)
Co-authored-by: Michael Le <michael.le647@gmail.com>
2023-09-30 23:52:56 +00:00
Björn Harrtell
c4211538bd TS: Add missing generate files (#8075)
Co-authored-by: Michael Le <michael.le647@gmail.com>
2023-09-30 10:51:32 -07:00
Artem Shilkin
bcb9ef1876 moved function to namespace (#8068) 2023-09-29 07:50:06 -07:00
Elior Schneider
c5441dc199 corrected a typo (#8063) 2023-09-29 07:40:02 -07:00
Artem Shilkin
7f417e3397 added explicit cast (#8066)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-09-29 07:39:38 -07:00
Artem Shilkin
3c35a143ea removed decrement of rvalue-pointer (#8067)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-09-29 07:34:16 -07:00
Markus Junginger
56e2bc30b0 C++ strict conversion fixes for flatbuffer_builder.h (#8062) (#8065)
Enables to compile flatbuffer_builder.h with strict settings -Wconversion -Wsign-conversion.
Also, add asserts to verify the conversions.
2023-09-29 07:30:23 -07:00
xaphier
eb40a54672 Add constexpr for bitmask operators (#8037)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-09-28 23:17:52 -07:00
Pavlo Bashmakov
15f16f149e Fix misalignment of small structs in a Vector (C++) (#7883)
* Rare fix: kick fix test

* Rare fix: real fix

* Rare fix: separate test

* Rare fix: remove comments

* Rare fix: updates

* Rare fix: less

* Rare fix: size_t switch to uoffset_t

* Rare fix: swap exp/val

* Rare fix: add annotated before/after

* Rare fix: remove unnecessary changes

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-09-28 22:53:50 -07:00
Derek Bailey
053d39adaf Update build.yml
Update to clang-14 as clang-12 is no longer supported
2023-09-28 22:26:28 -07:00
mustiikhalil
6f71b76e6f Allow reading unaligned buffers starting from swift 5.7, while keeping the creating aligned since its created by the library (#8061)
Addresses a warning on xcode 15 regarding copying a pointer without safeguards

Address PR comments regarding initializing buffers with flag

Adds a test case for copying unaligned buffers

Formatting code
2023-09-27 01:50:03 -04:00
Michael Le
4b7d8e0df9 Fix nim workflow (#8098)
* Fix nim workflow

* Fix yaml
2023-09-22 22:18:30 -07:00
dependabot[bot]
0def91105f Bump google.golang.org/grpc in /grpc/examples/go/greeter/models (#8025)
Bumps [google.golang.org/grpc](https://github.com/grpc/grpc-go) from 1.35.0 to 1.53.0.
- [Release notes](https://github.com/grpc/grpc-go/releases)
- [Commits](https://github.com/grpc/grpc-go/compare/v1.35.0...v1.53.0)

---
updated-dependencies:
- dependency-name: google.golang.org/grpc
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Michael Le <michael.le647@gmail.com>
2023-09-21 20:41:18 +00:00
dependabot[bot]
8176a204fc Bump google.golang.org/grpc in /grpc/examples/go/greeter/client (#8026)
Bumps [google.golang.org/grpc](https://github.com/grpc/grpc-go) from 1.35.0 to 1.53.0.
- [Release notes](https://github.com/grpc/grpc-go/releases)
- [Commits](https://github.com/grpc/grpc-go/compare/v1.35.0...v1.53.0)

---
updated-dependencies:
- dependency-name: google.golang.org/grpc
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Michael Le <michael.le647@gmail.com>
2023-09-20 22:04:44 -04:00
Ivo List
e8b2492cf1 Upgrade rules_go (#8092)
* Upgrade rules_go

* Revert go toolchain

---------

Co-authored-by: Michael Le <michael.le647@gmail.com>
2023-09-20 23:32:11 +00:00
dependabot[bot]
5d4386b1bc Bump google.golang.org/grpc in /grpc/examples/go/greeter/server (#8027)
Bumps [google.golang.org/grpc](https://github.com/grpc/grpc-go) from 1.39.0-dev to 1.53.0.
- [Release notes](https://github.com/grpc/grpc-go/releases)
- [Commits](https://github.com/grpc/grpc-go/compare/v1.39.0-dev...v1.53.0)

---
updated-dependencies:
- dependency-name: google.golang.org/grpc
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Michael Le <michael.le647@gmail.com>
2023-09-20 23:27:39 +00:00
Gowroji Sunil
a6a3989dd4 [bazel] Update Platforms (#8083)
* Update Platforms

* Update WORKSPACE

* indentation

* Update WORKSPACE

---------

Co-authored-by: Michael Le <michael.le647@gmail.com>
2023-09-20 16:22:25 -07:00
Wouter van Oortmerssen
696f47f1f7 Fix Nim warning 2023-09-17 21:19:28 -07:00
Wouter van Oortmerssen
a3dfcf3326 Update Lobster monster sample 2023-09-17 21:18:03 -07:00
Wouter van Oortmerssen
d3e8cb60a1 Lobster namespace change 2023-09-17 10:21:58 -07:00
Anton Bobukh
0343396e49 Fully qualify the offset type in FLATBUFFERS_VTABLE_UNDERLYING_TYPE (#8094) 2023-09-13 10:23:39 -07:00
jviel-beta
f625ff3330 [TS] Allows object API to set 0 for a null-default scalar. (#7864)
* Fixes bug where null default allows 0 as a value.

* Undoes one bit, adds null type allowance to addField<> default.

* Undoes IDE auto-format of imports.

* Adds generated changes after scripts/generate_code.py

* Removes unused symbol.

* Revert "Removes unused symbol."

This reverts commit 9cece17325.

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-09-12 19:58:55 +02:00
Philipp Schrader
362dd663f8 Fix BUILD.bazel style violations (#8081)
`buildifier` was complaining as follows:

    #### :bazel: buildifier: found 2 lint issues in your WORKSPACE, BUILD and *.bzl files
    <pre><code>tests/ts/bazel_repository_test_dir/BUILD:3:1: <a href="https://github.com/bazelbuild/buildtools/blob/master/WARNINGS.md#out-of-order-load">out-of-order-load</a>: Load statement is out of its lexicographical order.
    ts/BUILD.bazel:2:1: <a href="https://github.com/bazelbuild/buildtools/blob/master/WARNINGS.md#out-of-order-load">out-of-order-load</a>: Load statement is out of its lexicographical order.</pre></code>

This can be fixed locally like so:

    $ buildifier -lint fix $(git ls-files | grep -e '/BUILD.bazel$' -e '/BUILD$' -e '\<WORKSPACE$')

I also took this opportunity to fix one of the filenames.

I accidentally introduced these errors in #8078.
2023-08-28 09:20:10 +02:00
Philipp Schrader
5a8a395756 Upgrade the bazel-related dependencies (#8078)
This patch updates all the bazel-related dependencies to their latest
available versions. All tests still pass.

Fixes: #8076
2023-08-25 18:15:12 +02:00
Max Burke
afafd206a3 Optional omission of Typescript entrypoint (#8057) 2023-08-20 10:28:47 +02:00
OptoCloud
48da238920 Make eslint less pedantic (#8012)
* Disable eslint spam

* Generate TS example files
2023-07-10 15:48:16 +00:00
Derek Bailey
8836ddab41 Update stale.yml 2023-07-08 15:18:47 -07:00
Wouter van Oortmerssen
23922e7eba FlexBuffers: JSON output supports indentation 2023-06-14 18:12:55 -07:00
Wouter van Oortmerssen
f8fe811d5c FlexBuffers: allow getting size & undo of map in progress 2023-06-14 17:12:37 -07:00
Derek Bailey
0cc525b722 fix android typo 2023-05-31 19:31:47 +00:00
Derek Bailey
28861d1d7d various fixes (#7986) 2023-05-31 11:52:05 -07:00
James Kuszmaul
204473cdb5 [Bazel] Fix gen_reflections for flatbuffers_ts_library (#7981)
If you used flatbuffers_ts_library with gen_reflections = True then it
attempted to use the flat-file compiler rather than flatc itself.

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-05-31 18:07:37 +00:00
Paulo Pinheiro
85088a196d Small optimization on "deserialization" and fix on benchmarks again (#7982)
* [Kotlin] Small optimizations and benchmark on deserialization

* [Kotlin] Remove redudant assign() method (use init() instead)

* [Kotlin] Fix benchmark run after change in flatbuffers-java deps

Commit 6e214c3a49 fixes Kotlin build,
but makes the kotlin-benchmark plugin misses the java classes at
runtime, causing NotClassFoundError. The alternative to solve the issue
is to read java's pom.xml to get the latest java version and use it
as dependency. With that we avoid compilation errors on a new version and
keep benchmark plugin happy.
2023-05-31 11:02:39 -07:00
Paulo Pinheiro
6e214c3a49 [Kotlin] Add java source on benchmark module instead of using version jar (#7978)
By using specific jar version to use java's runtime on the benchmark
module we let CI break when new versions are released. So we are using
source directly instead
2023-05-26 14:07:18 -07:00
Derek Bailey
96294e9f84 Add ForceVectorAlignment64 and test (#7977) 2023-05-26 11:49:06 -07:00
Paulo Pinheiro
b7856f8e27 Add Kotlin multiplatform support (#7969)
* [Kotlin] Introduction to Kotlin Multiplaform

The first implementation of the Kotlin code generation was made years
ago at the time Kotlin Multiplaform was not stable and Kotlin is mostly
used on JVM-based targets. For this reason the generated code uses java
based runtime.

That design decision comes with many drawbacks, leaving the code
generated more java-like and making it impossible to use more advanced
features of the Kotlin language.

In this change we are adding two parts: A pure, multi-plaform, Kotlin
runtime and a new code generator to accompany it.

* [Kotlin] Remove scalar sign cast from code generation

Now that we have a new runtime the accepts unsigned types, we don't
need to code generate casting back and from signed scalars. This
MR removes this from both code generations and adds the necessary
API to the runtime.

* [Kotlin] Use offset on public API to represent buffer position

Currently, kotlin was following Java's approach of representing objects,
vectors, tables as "Int" (the position of it in the buffer). This change
replaces naked Int with Offset<T>, offering a type-safe API. So,
instead of

fun Table.createTable(b: FlatBufferBuilder, subTable: Int)

We will have

fun Table.createTable(b: FlatBufferBuilder, subTable: Offset<SubTable>)

Making impossible to accidentally switch parameters.

The performance should be similar to use Int as we are using value
class for Offset and ArrayOffset, which most of the time translate to
Int in the bytecode.

* [Kotlin] Add builder for tables

Add builder constructor to make create of table more ergonomic.
For example the movie sample for the test set could be written as:

Movie.createMovie(fbb,
    mainCharacterType = Character_.MuLan,
    mainCharacter = att) {
    charactersType = charsType
    this.characters = characters
}

instead of:

Movie.startMovie(fbb)
Movie.addMainCharacterType(fbb, Character_.MuLan)
Movie.addMainCharacter(fbb, att as Offset<Any>)
Movie.addCharactersType(fbb, charsType)
Movie.addCharacters(fbb, charsVec)
Movie.endMovie(fbb)

* [Kotlin] Move enum types to value class

Moving to flatbuffer enums to value class adds type safety for parameters
with minimum to no performance impact.

* [Kotlin] Simplify Union parameters to avoid naked casting

Just a small change on the APIs that receive union as parameters,
creating a typealias UnionOffset to avoid using Offset<Any>. To "convert"
an table offset to an union, one just call Offset.toUnion().

* [Kotlin] Apply clang-format on kotlin code generators

* [Kotlin] Update kotlin generator to follow official naming conventions

Updating directory, package and enum naming to follow Kotlin official
convention.

https://kotlinlang.org/docs/coding-conventions.html#naming-rules

* [Kotlin] Add fixes to improve performance

1 - Add benchmark comparing serialization between Java & Kotlin
2 - ReadWriteBuffer does not auto-grow (thus avoid check size in every op)
3 - Add specialized add functions on FlatBufferBuilder to avoid boxing
offsets.
4 - Remove a few Kotlin syntax sugar that generated performance penalties.

* [Kotlin] Remove builder from Kotlin KMP and add some optimizations
to avoid boxing of Offset classes

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-05-26 11:00:33 -07:00
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
Derek Bailey
ee848a02e1 FlatBuffers Version 23.1.21 (#7796) 2023-01-21 12:46:57 -08:00
Björn Harrtell
ef76b5ece4 [TS/JS] Entry point per namespace and reworked 1.x compatible single file build (#7510)
* [TS/JS] Entry point per namespace

* Fix handling of outputpath and array_test

* Attempt to fix generate_code

* Fix cwd for ts in generate_code

* Attempt to fixup bazel and some docs

* Add --ts-flat-files to bazel build to get bundle

* Move to DEFAULT_FLATC_TS_ARGS

* Attempt to add esbuild

* Attempt to use npm instead

* Remove futile attempt to add esbuild

* Attempt to as bazel esbuild

* Shuffle

* Upgrade bazel deps

* Revert failed attempts to get bazel working

* Ignore flatc tests for now

* Add esbuild dependency

* `package.json` Include esbuild

* `WORKSPACE` Add fetching esbuild binary

* Update WORKSPACE

* Unfreeze Lockfile

* Update WORKSPACE

* Update BUILD.bazel

* Rework to suggest instead of running external bundler

* Add esbuild generation to test script

* Prelim bundle test

* Run test JavaScriptTest from flatbuffers 1.x

* Deps upgrade

* Clang format fix

* Revert bazel changes

* Fix newline

* Generate with type declarations

* Handle "empty" root namespace

* Adjust tests for typescript_keywords.ts

* Separate test procedure for old node resolution module output

* Fix rel path for root level re-exports

* Bazel support for esbuild-based flatc

Unfortunately, we lose typing information because the new esbuild method
of generating single files does not generate type information.

The method used here is a bit hack-ish because it relies on parsing the
console output of flatc to figure out what to do.

* Try to fix bazel build for when node isn't present on host

* Auto formatting fixes

* Fix missing generated code

Co-authored-by: Derek Bailey <derekbailey@google.com>
Co-authored-by: James Kuszmaul <jabukuszmaul+collab@gmail.com>
2023-01-21 12:22:22 -08:00
Michael Le
1703662285 Flatbuffers Version 23.1.20 (#7794)
* Flatbuffers Version 23.1.20

* Fix warnings

* Fix warnings
2023-01-21 12:03:17 -08:00
liu
991b39edbe Use CMAKE_CURRENT_SOURCE_DIR in benchmark cpp path (#7781)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-01-19 07:48:09 +00:00
Michael Le
81799203f1 Remove go.mod to resolve ambiguous import issue (#7783) 2023-01-18 23:40:50 -08:00
Saman
62e4d2e5b2 Fix binary output different in different platform (#7718)
* Fix binary output different in different platform, due to the nan serialization

* Add check generated code on windows ci

* Remove resdundant script

* Fix eof, and check script

* Minor bug in gen code script

* Fix windows script, remove redundant scripts

* Undelete redundante codes

* Fix github action

* Ignore eof generate grpc

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-01-10 12:04:25 -08:00
Ben Beasley
40758674b1 Fix some identity/equality confusion in Python tests (#7768)
Comparing short strings, small integers, and Booleans by identity
(memory address) can work due to optimizations in the Python
interpreter, but it is neither formally correct nor reliable. Use
equality comparisons instead.

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-01-10 19:36:39 +00:00
Ben Beasley
4e75867bd2 Stop using deprecated imp package in Python tests (#7769)
It is deprecated in favour of importlib and slated for removal in Python
3.12. Since the return value of imp.find_module('numpy') is unused, the
only effect of calling this function is to raise an ImportError when
numpy is not available; importing numpy directly is already sufficient
to do this.

The imp package is still used in python/flatbuffers/compat.py, but only
on Python 2, where it is not deprecated and will not be removed.

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-01-10 11:30:30 -08:00
José Luis Millán
b17d59b18c [TS]: builder, Fix requiredField(). Verity that the field is present in the vtable (#7739) (#7752)
* [TS]: Fix vtable creation for consecutive required fileds (#7739)

* handle feedback

* comment the schema

* comment change in builder.ts

* [TS]: builder, Fix requiredField()

Verifty that the field is present in the vtable.

* restore monsterdata binary file

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-01-10 10:43:17 -08:00
Ben Beasley
b23493a7d2 Fix Python host-endianness dependencies (#7773)
* In Python tests, use host-endian-independent dtypes

* Fix host endianness dependence in Python flexbuffers

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-01-10 10:20:08 -08:00
Anton Bobukh
b50b6be60a [Kotlin] Control the generation of reflection with --reflect-names (#7775)
* [Kotlin] Control the generation of reflection with --reflect-names.
Tested:
```
$ cmake -G "Unix Makefiles" && make && ./tests/flatc/main.py
...
KotlinTests.EnumValAttributes
 [PASSED]
KotlinTests.EnumValAttributes_ReflectNames
 [PASSED]
KotlinTests: 2 of 2 passsed
...

35 of 35 tests passed
```

* [Kotlin] Fix SampleBinary by converting Byte to UByte for ubyte fields.

* [Kotlin] Annotate all generated classes with kotlin.ExperimentalUnsignedTypes.
2023-01-10 10:03:39 -08:00
Michał Górny
7bf83f5ea0 Use full project version as SOVERSION for the shared library (#7777)
Since flatbuffers is using calendar versioning and does not provide
any ABI stability guarantees, use the complete version as SOVERSION
for the shared library rather than just the major component. This
prevents breaking reverse dependencies on incompatible upgrades.

Fixes #7759
2023-01-10 09:31:49 -08:00
Ben Beasley
ca6381bcc8 Fix a typo in a Python test name (#7774) 2023-01-09 10:32:50 -08:00
Derek Bailey
3b8644d32c Defined CodeGenerator Interface and implement C++ (#7771) 2023-01-08 15:01:33 -08:00
Derek Bailey
641fbe4658 Refactor FlatC to receive FlatCOptions (#7770)
* Refactor FlatC to receive `FlatCOptions`

* switch to c++11 unique_ptr
2023-01-08 13:29:00 -08:00
Saman
5638a6a900 Minor improvement (#7766) 2023-01-07 19:40:03 -08:00
Chris
c2668fc0e2 Add ts-no-import-ext flag (#7748)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-01-07 13:42:28 -08:00
Stefan F
b5802b57f2 Fix [C#] Object API - Invalid Property Name used in UnPackTo for unio… (#7751)
* Fix [C#] Object API - Invalid Property Name used in UnPackTo for union fieldhttps://github.com/google/flatbuffers/issues/7750, also fixes invalid Code generated in WriteJson for Unions named Value.

* Test added: new schema union_value_collision.fbs with a Union named Value and a union field named value. The generated C# code now compiles when NetTest.bat. The Code generated with an older flatc.exe didn't compile because of a mismatch of the property name (Value vs. Value_).

* branch was not up-to-date with master

* BASE_OPTS + CPP_OPTS removed and union_value_collision_generated.h deleted

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-01-07 12:37:22 -08:00
Derek Bailey
06f2a3dce9 Increase float to string precision to 17 2023-01-07 12:21:25 -08:00
Derek Bailey
75af533e95 emit global scoped ::flatbuffers in c++ (#7764) 2023-01-07 12:17:07 -08:00
Derek Bailey
c95cf661af Annotated Binaries emit field names instead of type names (#7763) 2023-01-07 12:01:00 -08:00
jalitriver
920f3827a0 [C++] Add Command-Line Flag to Suppress MIN and MAX Enums (#7705)
Add the --no-minmax-values flag to prevent flatc from generating C++
enums with MIN and MAX enumerated values that otherwise would be set
to the inclusive lower and upper bound respectively of the enum.

This command-line flag is needed to avoid collisions when an enum that
is being ported to FlatBuffers already has a MIN or MAX enumerated
value.

It is also needed to work around a long-standing problem with
magic_enum that causes magic_enum to not see enumerated values that
are not unique.  For example, if FlatBuffers sets MIN = FOO and MAX =
BAR, MIN and FOO share the same underlying value so they are not
unique.  The same is true of MAX and BAR.  This prevents magic_enum
from converting FOO and BAR to and from strings as well as causing
magic_enum to return a count of enumerated values that is two fewer
than it should be.

Co-authored-by: Paul Serice <paul@serice.net>
2023-01-07 10:33:11 -08:00
Max Burke
81724e5b20 Ensure that empty modules can build in TypeScript isolatedModules mode (#7726) 2023-01-06 16:42:26 -08:00
mustiikhalil
4d6a7aa8b7 Removes Dead code & regenerate code (#7744)
Formats the swift project

Update Sample files

Update docc documentation

Updates swift docs in the website

Updates code for Wasm
2023-01-06 16:40:40 -08:00
Florian Wagner
e61b00359b [Kotlin] Improve field nullability based on (required) (#7658)
* [Kotlin] Only generate nullable return types if the field is not required

* [Kotlin] Fix generated code formatting according to kotlin style guide

Co-authored-by: Derek Bailey <derekbailey@google.com>
Co-authored-by: Paulo Pinheiro <paulovictor.pinheiro@gmail.com>
2023-01-06 04:16:31 +00:00
Saman
74b5195089 Fix operator==() generated for field of fixed sized array (#7749)
* Fix operator==() generated for field of fixed sized array

* Compare address

* noexcept

* Grammer

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-01-05 20:11:11 -08:00
Anton Bobukh
07d9485146 Expand wildcard imports in the generated Kotlin files. (#7757)
Tested:

```
$ cmake -G "Unix Makefiles" && make && ./flattests
...
[ 99%] Linking CXX executable flatsamplebinary
[100%] Built target flatsamplebinary
ALL TESTS PASSED
```

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-01-05 14:34:44 -08:00
Derek Bailey
82da3da3f6 Update Readme.md for versioning
Updated the front readme doc about the non-semver versioning so that the rationale is more apparent to users.
2023-01-05 14:24:56 -08:00
Paulo Pinheiro
a809a2d3f7 Add pointer reference to sibling union field on FieldDef (#7755)
To make it simple to map between a union field and its union type
field we are adding a pointer to FieldDef to point to each other. For
all other types the pointer will be nullptr.

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-01-05 14:21:23 -08:00
Derek Bailey
af9ceabeef FlatBuffers Version 23.1.4 (#7758) 2023-01-04 15:22:46 -08:00
Michael Le
3b2eb77595 Fix go.mod name (#7756) 2023-01-04 09:27:44 -08:00
Michael Le
6420fa5c88 [Go]Add go.mod (#7720)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-01-03 20:56:11 -08:00
Robin Giese
01589630ba Fix "'flatbuffers::FieldDef* field' shadows a parameter" (#7740) 2023-01-03 20:00:54 -08:00
RishabhDeep Singh
e0d68bdda2 Add link to building guide (#7733) 2022-12-22 14:06:57 -08:00
James Kuszmaul
e43a80c322 [TS] Fix getFullyQualifiedName codegen for typescript (#7730)
#7451 caused getFullyQualifiedName to return a name with underscores,
not periods. Because the fully qualified name is a property of
FlatBuffers, not the language being codegen'd for, it should use
periods. Fixes #7564.

Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-12-22 20:59:40 +00:00
RishabhDeep Singh
449d5649d6 Fixed test cases (#7732)
* Fix Cannot find symbol and test case

* Add generated tests

Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-12-22 20:51:39 +00:00
Michael Le
96d438df47 Perform nil check on string fields when packing (#7719)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-12-22 20:28:00 +00:00
engedy
4e396d47bc Add CI step to build with -DFLATBUFFERS_NO_FILE_TESTS. (#7729)
* Add CI step to build with -DFLATBUFFERS_NO_FILE_TESTS

* Fix cmake syntax

* Further fix cmake argumetns

* Add workaround for unused-parameter.

* Remove build matrix

Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-12-22 08:48:48 -08:00
engedy
b47ba1d5ff Add include guards around DoNotRequireEofTest (#7728)
Guard DoNotRequireEofTest against -Wunused-function on platforms without file tests.
2022-12-21 14:59:34 -08:00
Casper
a078130c87 Fix Rust codegen escaping field in tables. (#7659)
* Fix Rust codegen escaping  field in tables.

* other gencode

* gencode

* removed a debug print

* regen code

Co-authored-by: Casper Neo <cneo@google.com>
Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-12-15 06:04:57 +00:00
Saman
9ed76559df Add clang-tidy, fix some bugpron problems. (#7708)
* Add clang-tidy, fix some bugpron problems.

* Fix more issues

* Fix some more issues :))

* Minimal pr to just add clang-tidy

Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-12-14 21:58:55 -08:00
mogemimi
9927747d4e [C++] Fix clang -Wnewline-eof warning (#7711)
* Fix clang -Wnewline-eof warning

* Enable -Wnewline-eof warning

Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-12-14 21:35:54 -08:00
Wen Sun
52d1b77941 Add CI job to build linux and run unit test on s390x (#7707)
* create job to build linux and run unit test on s390x

* update

* update

* update

* update

* update

* print out machine type

* create regression test to build a big endian arch and run unit tests daily

* rename and schedule run on pr merged and on request

* udpate

Co-authored-by: Wen Sun <sunwen@google.com>
Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-12-14 14:56:31 -08:00
Jared Junyoung Lim
40aa964057 Add Ref.AsStringBytes to flatbuffers.flexbuffers Python API (#7713)
* Add Ref.AsStringBytes to flatbuffers.flexbuffers Python API

* Append Bytes to AsStringBytes return value

Co-authored-by: Jared Junyoung Lim <jaredlim@google.com>
2022-12-14 14:42:56 -08:00
Michael Le
e1a2f688e0 [Go] Fix bug where bytes wasn't being imported when using --gen-onefile flag (#7706)
* Fix bug one file import bug

* Create reset import function and add braces
2022-12-12 23:06:48 -08:00
Saman
c0797b22ae fix clang format plus implicit cast error. (#7704) 2022-12-12 21:22:24 -08:00
Maxim Zaks
97ee210826 Fix a bug where a floating point number was cast to int and the value was stored incorrectly because of low byte width. (#7703)
Reported in https://github.com/google/flatbuffers/issues/7690
2022-12-12 21:20:26 -08:00
Max Burke
3be296ec8a [Rust] Restore public visibility of previously-public fields (#7700)
* Restore public visibility of previously-public fields

* code review feedback
2022-12-08 18:20:14 -05:00
Derek Bailey
acf39ff056 FlatBuffers Version 22.12.06 (#7702) 2022-12-06 22:54:49 -08:00
Derek Bailey
0e79e56427 inline initialize byte_width 2022-12-06 22:18:11 -08:00
郭浩伟
aadc4cb8be fix: byte_width_ = 1U << static_cast<BitWidth>(packed_type & 3) implicit conversion loses integer precision: 'unsigned int' to 'uint8_t' (aka 'unsigned char') [-Werror,-Wimplicit-int-conversion] (#7697)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-12-06 21:19:54 -08:00
Wen Sun
b5ebd3fd78 [C++] Update to address comparator failure in big endian (#7681)
* update unit test and generated file to test is extra endianswap can help resolve issue

* remove EndianScalar wrapper from Get method

* remove endianscalar wrapper

* update

* update

* use Array instead

* clang format

* address error

* clang

* update

* manually generate

* Move Nim to completed language

* Add swift link

* address comments

* update unit test

* address comment

* address comment

* regenerate file

* use auto instead of size_t

* use uint32_t instead

* update

* format

* delete extra whitespace

Co-authored-by: Wen Sun <sunwen@google.com>
Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-12-06 14:02:16 -08:00
Michael Mickelson
11394575bc Fix "Download Doxygen" URL (#7699) 2022-12-06 14:01:12 -08:00
James Kuszmaul
5b7b36e8be Upgrade rules_go for Bazel 7.0 support (#7691)
Fixes: #7664 (hopefully)

Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-12-05 16:56:02 -08:00
RishabhDeep Singh
c0230d839b Refactor src/idl_gen_cpp.cpp (#7693)
* Refactor for loops and simplify code

* Refactor for loops and simplify code

* Fix for loop and reformat

* reformat code
2022-12-06 00:43:38 +00:00
RishabhDeep Singh
a8d49f2972 Add LICENSE.txt to python (#7692)
* Add LICENSE.txt to python

* Remove LICENSE.txt from python path and used the root LICENSE.txt file
2022-12-05 16:37:21 -08:00
Derek Bailey
416c6020eb Add swift link 2022-12-02 20:52:20 -08:00
Derek Bailey
6d95867a8f Move Nim to completed language 2022-12-02 20:49:03 -08:00
Derek Bailey
2eaf790638 Fix confrom failure for nullptr dereference. (#7688) 2022-12-01 20:21:48 -08:00
Derek Bailey
3b2ced0131 Update missing C# namespace to Google.FlatBuffers 2022-12-01 20:04:49 -08:00
Michael Le
00af4e23b3 Remove --gen-name-strings flag from cmake command for generating union_vector_generated.h (#7684)
* Sync make outputs with master

* Remove --gen-name-string flag from CMAKE
2022-11-30 20:57:06 -08:00
Sergei Trofimovich
7e00b754f0 tests/reflection_test.h: add missing <stdint.h> include (#7680)
Without the change build fails on weekly `gcc-13` snapshots as:

    In file included from /build/flatbuffers/tests/reflection_test.cpp:1:
    tests/reflection_test.h:9:57: error: 'uint8_t' has not been declared
        9 | void ReflectionTest(const std::string& tests_data_path, uint8_t *flatbuf, size_t length);
          |                                                         ^~~~~~~
2022-11-30 18:47:10 -08:00
Louis Laugesen
cf89d1e756 Fix PHP byte validation and reenable builds (#7670)
* Fix PHP byte validation and reenable builds

* Use checkout@v3

Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-11-29 08:12:28 -08:00
sssooonnnggg
ad6054c600 chore: emit more reasonable error message when using incomplete type in struct (#7678)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-11-29 04:59:53 +00:00
Michael Le
c3a01c7228 Use FinshedBytes() in go-echo example instead of manually encoding offset (#7660)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-11-29 02:29:48 +00:00
Saman
533f75d91b Fix java import wild card (#7672)
* Fix java import wild card

* fix java include

* Fix some import problems

* clang-format

* Sort imports

Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-11-28 17:27:55 -08:00
Derek Bailey
fcab80f1bb build.yml: MacOs Build Inplace (#7677)
* `build.yml`: MacOs Build Inplace

* Update build.yml
2022-11-28 16:38:56 -08:00
Derek Bailey
5d2d0b92b1 build.yml Update dependencies (#7674)
* `build.yml` Update dependencies

* Update build.yml

* Update build.yml

* `build.yml`: Use macos-11

* Update build.yml
2022-11-28 15:34:32 -08:00
Derek Bailey
ae6662374d add buildkite badge 2022-11-23 13:11:56 -08:00
Casper
7b6c9f4a3c Rurel (#7663)
* Update release script to update Rust version (it still needs to be published after)

* Also update rust while I'm at it

Co-authored-by: Casper Neo <cneo@google.com>
2022-11-23 12:03:54 -08:00
Derek Bailey
5a42b2c76c Specify min android SDK version of 14 2022-11-23 11:54:36 -08:00
Derek Bailey
8f625561d0 FlatBuffers Version 22.11.23 (#7662) 2022-11-23 11:32:19 -08:00
Derek Bailey
9d2c04d629 FlatBuffers Version 22.11.22 2022-11-22 14:40:01 -08:00
Michael Le
e000458bb1 Add --go-module-name flag to support generating Go module compatible code (#7651)
* Add --go-module-name flag to support generating code for go modules

* Rename echo example folder

* Grammar

* Update readme for go-echo example

* Update readme for go-echo example

* Re-enable go modules after test is done
2022-11-22 14:28:01 -08:00
Michael Le
60975d6f7e Add key lookup support for tables in Go (#7644)
* Add support for key lookup for tables in Go

* Run clang format

* Run go fmt on tests

* Remove TODO in tests

* Update LookupByKey API

* Update LookupByKey API

* Don't use resolvePointer in expectEq

* Use generated getters instead of reading values directly from buffer

* Fix typo

Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-11-22 14:08:19 -08:00
Saman
1cba8b2b49 Fix go generator undefined Package name, also throwing exception (#7632)
* Fix go generator undefined Package, also throw exception in specific examples.

* Add test for go generator import problem

* Add new version of generated go file. Fix conflict.

* Add executable permission to generate_code.py script.

* Improve test quality, remove unwanted generated files, better naming

* Fix comments

* clang format

Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-11-22 13:21:25 -08:00
TJKoury
eead6c6219 updated method call (#7642) 2022-11-22 13:01:32 -08:00
Alex Ames
bb9b9dad5f Fixed the BytesConsumed function, which was pointing slightly ahead. (#7657)
The BytesConsumed function uses the `cursor_` to determine how many
bytes have been consumed by the parser, in case the user of the Parser
object wants to step over the parsed flatbuffer that is embedded in some
larger string. However, the `cursor_` is always one token ahead, so that
it can determine how to consume it. It points at the token that is about
to be consumed, which is ahead of the last byte consumed.

For example, if you had a string containing these two json objects and
parsed them...

    "{\"key\":\"value\"},{\"key\":\"value\"}"

...then the `cursor_` would be pointing at the comma between the two
tables. If you were to hold a pointer to the beginning of the string and
add `BytesConsumed()` to it like so:

    const char* json = // ...
    parser.ParseJson(json);
    json += parser.BytesConsumed();

then the pointer would skip over the comma, which is not the expected
behavior. It should only consume the table itself.

The solution is simple: Just hold onto a previous cursor location and
use that for the `BytesConsumed()` call. The previous cursor location
just needs to be set to the cursor_ location each time the cursor_ is
about to be updated. This will result in `BytesConsumed()` returning
the correct number of bytes without the off-by-one-token error.

Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-11-22 20:11:14 +00:00
tira-misu
ade9e19be0 [C#] Fix collision of member if union name is "Value" (#7648)
* 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

* [C#] Fix collision of member if enum name is "Value"

* Fix due to style guide

Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-11-22 20:00:13 +00:00
Wen Sun
eb1abb51ea Add support for using array of scalar as key field in Cpp (#7623)
* add support for using array of scalar as key field

* update cmakelist and test.cpp to include the tests

* update bazel rule

* address comments

* clang format

* delete comment

* delete comment

* address the rest of the commnets

* address comments

* update naming in test file

* format build file

* buildifier

* make keycomparelessthan call keycomparewithvalue

* update to use flatbuffer array instead of raw pointer

* clang

* format

* revert format

* revert format

* update

* run generate_code.py

* run code generator

* revert changes by generate_code.py

* fist run make flatc and then run generate_code.py

Co-authored-by: Wen Sun <sunwen@google.com>
2022-11-18 11:04:46 -08:00
Saman
1fa6091000 Fix schema to binary test, when build and run from all directories. specially when add to other projects. (#7650) 2022-11-17 20:24:48 -08:00
tira-misu
634c2ee7e3 Put documentation to bfbs if it is not empty (#7649)
* 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

* Put documentation to bfbs if it is not empty

* Fix monster test bfbs reference files

* Fix generated monster test files

Why they are different when generating it with linux and windows executable?
2022-11-17 15:55:42 -08:00
Derek Bailey
6f895f54c2 Add _deps/ to gitignore 2022-11-13 12:00:07 -08:00
Gh0u1L5
41d6903294 [Go] Fix GenNativeUnionUnPack for imported union type. (#7579)
* Fix GenNativeUnionUnPack for imported union type.

* Update test results.

Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-11-13 11:52:02 -08:00
Saman
7b038e3277 Fix import problem in dart generated files. (fixes #7609). (#7621)
* Fix import problem in dart generated files. (fixes #7609).

* Fix naming.

* Fix minor changes in generated files.

* Add some tests. Fix minor problems.

* Fix minor format problem plus import alias issue.

* Minor fix in dart code generator, remove java from examples

* remove java and go generated files

* Fix dart tests.

* Fix spell problem.

* Remove excessive tests :))

Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-11-13 19:21:57 +00:00
mr-swifter
74756e5d1b [swift] fix broken swift test build (#7633) (#7634)
* [swift] fix broken swift test build (#7633)

* [swift] fix unused variable (#7633)

* [swift] update generated code (#7633)

* [swift] add binary & json test for nan, inf, -inf for swift (#7633)

* [swift] use just '.infinity' instead of '+.infinity' (#7633)

* [swift] remove commented code (#7633)

Co-authored-by: Derek Bailey <derekbailey@google.com>
Co-authored-by: mustiikhalil <26250654+mustiikhalil@users.noreply.github.com>
2022-11-11 18:36:47 +01:00
RishabhDeep Singh
879622fc57 Fixes #7345 to add the option to minify enums (#7566)
* Added cpp minified enums

* Update generated files

* remove initializer and fix comma

* Fix .gitignore

* Fix comma

* Add tests for cpp minify enums
2022-11-11 04:47:28 +00:00
M. Şamil Ateşoğlu
83e7a98f69 [C++] Minireflect: Add option to indent when converting table to string (#7602)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-11-11 02:57:29 +00:00
Alex-Ratcliffe
f20b0a45b3 Add comparison operator to python objects under --gen-compare option (#7610)
* Add comparison operator to python code generator

* Missing semi-colon

* Regenerate test examples

Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-11-11 02:47:53 +00:00
Rudi Heitbaum
207708efef [CMake]: only warn when the working directory in a git worktree (#7562)
Signed-off-by: Rudi Heitbaum <rudi@heitbaum.com>

Signed-off-by: Rudi Heitbaum <rudi@heitbaum.com>
Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-11-11 02:21:38 +00:00
laurentsimon
225578a8b3 Temporary fix for SLSA generators (#7636)
* Temporary fix for SLSA generators

Sigstore made a breaking change as part of their recent GA announcement. We need a temporary fix to avoid builder failure (see slsa-framework/slsa-github-generator#1163)

/cc @asraa

* Update build.yml
2022-11-10 20:09:01 -06:00
mustiikhalil
459e8acc37 Uses swift build command directly in the CI (#7635) 2022-11-10 14:16:42 -08:00
James Kuszmaul
8aa8b9139e Fix handling of +/-inf defaults in TS/rust/go/dart codegen (#7588)
+/-inf were not being handled, and so invalid typescript was being
generated when a float/double had an infinite default value. NaN was
being handled correctly.

Co-authored-by: Derek Bailey <derekbailey@google.com>
Co-authored-by: Casper <casperneo@uchicago.edu>
2022-11-08 10:59:46 -08:00
Michael Le
001adf782d Add support for parsing proto map fields (#7613)
* Add support for proto 3 map to fbs gen

* Run clang-format

* Update proto golden test

* Rename variables

* Remove iostream

* Remove iostream

* Run clang format

Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-11-08 10:51:24 -08:00
Ben Beasley
dbc58ab77c Fix help output for --gen-includes (#7611)
Fixes the --help output documenting the deprecated --gen-includes
option, in which the option name contained a typo (--gen-inclues).
2022-11-08 18:16:17 +00:00
Ben Beasley
2facfeec7e Fix missing spaces in flatc help text (#7612)
* Fix error in --json-nested-bytes help text

Correct “bytesin” to “bytes in”

* Fix missing space in --no-leak-private-annotation help text
2022-11-08 17:59:48 +00:00
刘帅
4de2814c7b Fix: arduino platform build (#7625) 2022-11-08 09:53:53 -08:00
Valeriy Van
37b1acdaff Fix current official name of macOS (#7627)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-11-08 09:49:27 -08:00
Even Rouault
a22434e2a1 Add missing #include <algorithm> for std::min/std::max uses, and #include <limits> for std::numeric_limits<> (#7624) 2022-11-08 09:36:35 -08:00
Casper
214cc94681 Bump Rust version to 22.10.26 before publication (#7622) 2022-11-03 16:24:00 +00:00
Alex Ames
a4ff275d9b Added option to not requires an EoF token when parsing JSON (#7620)
Previously when parsing a JSON representation of a Flatbuffer, the
parser required that the input string contain one and only one root
table. This change adds a flag that removes that requirement, so that
if a Flatbuffer table is embedded in some larger string the parser will
simply stop parsing once it reaches the end of the root table, and does
not validate that it has reached the end of the string.

This change also adds a BytesConsumed function, which returns the number
of bytes the parser consumed. This is useful if the table embedded in
some larger string that is being parsed, and that outer parser needs to
know how many bytes the table was so that it can step over it.
2022-11-03 11:57:46 -04:00
inaryart
15f32c6907 python: object generation prefix and suffix (#7565)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-10-29 00:37:27 +00:00
Michael Le
051afd8825 Add CreateSharedString to python builder (#7608)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-10-29 00:28:35 +00:00
Alejandro Ramallo
728c033ad6 Add check for presence of realpath to CMakeLists.txt to support more platforms (#7603)
* add automatic check for realpath in CMakeLists

* added win32 check

Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-10-29 00:23:36 +00:00
Michael Le
4c514483d8 Update DartTest.sh golden files (#7606) 2022-10-29 00:15:14 +00:00
Bulent Vural
c2d9c20803 [TS] Add support for fixed length arrays on Typescript (#5864) (#7021) (#7581)
* [TS] Add support for fixed length arrays on Typescript (#5864) (#7021)

    * Typescript / Javascript don't have fixed arrays but it is important to support these languages for compatibility.

    * Generated TS code checks the length of the given array and do truncating / padding to conform to the schema.

    * Supports the both standard API and Object Based API.

    * Added a test.

    Co-authored-by: Mehmet Baker <mehmet.baker@zerodensity.tv>
    Signed-off-by: Bulent Vural <bulent.vural@zerodensity.tv>

Signed-off-by: Bülent Vural <bulent.vural@zerodensity.tv>

* Formatting & readability fixes on idl_gen_ts.cpp

Signed-off-by: Bülent Vural <bulent.vural@zerodensity.tv>

* Added array_test_complex.bfbs

Signed-off-by: Bülent Vural <bulent.vural@zerodensity.tv>

* TS arrays_test_complex: Remove bfbs and use  fbs directly

Signed-off-by: Bülent Vural <bulent.vural@zerodensity.tv>

Signed-off-by: Bülent Vural <bulent.vural@zerodensity.tv>
2022-10-28 17:00:24 -07:00
Derek Bailey
e34ae4c6b6 build.yml: Fix missing 'v' in version 2022-10-27 16:14:26 -07:00
Derek Bailey
e54536127c build.yml Update to Kotlin Wrapper 1.0.5 2022-10-27 13:55:41 -07:00
Derek Bailey
49d9f941c0 release.yml Use env var for passphrase 2022-10-26 22:50:05 -07:00
Derek Bailey
cefc21c1f9 release.yml Add GPG key for Maven 2022-10-26 22:37:11 -07:00
Derek Bailey
3e64fa7246 release.yml: Add Maven Steps 2022-10-26 22:27:20 -07:00
Derek Bailey
b15f3c57ea release_yml Use new dotnet version 2022-10-26 17:15:51 -07:00
Derek Bailey
ff802c6802 release.yml Use NuGet Key directly 2022-10-26 17:05:08 -07:00
Derek Bailey
b401957d5f release.yml Changed Push to follow examples 2022-10-26 17:01:11 -07:00
Derek Bailey
8c8151f8f9 release.yml Fix nuget push command 2022-10-26 16:41:17 -07:00
Derek Bailey
ebb7c203d3 release.yml Add Nuget support 2022-10-26 16:36:35 -07:00
Derek Bailey
203241ed32 FlatBuffers Version 22.10.26 (#7607) 2022-10-26 16:02:38 -07:00
Derek Bailey
ac485609c4 setup.py: Define version directly
Define the version directly instead of loading from an environment variable and writing to a file.
2022-10-26 15:31:02 -07:00
Derek Bailey
de5b85aa66 release.yml: Switch to python directory 2022-10-26 15:29:02 -07:00
Derek Bailey
de3df2d88b release.yml: Add publishing to PyPi 2022-10-26 15:17:21 -07:00
Joshua Smith
043a24f2e4 [Python] Fixed the issue with nested unions relying on InitFromBuf. (#7576)
* feat: Fixed the issue with nested unions relying on InitFromBuf.
Problem: Issue #7569
Nested Unions were broken with the introduction of parsing buffers with an initial encoding offset.

Fix:
Revert the InitFromBuf method to the previous version and introduction of InitFromPackedBuf that allows
users to read types from packed buffers applying the offset automatically.

Test:
Added in TestNestedUnionTables to test the encoding and decoding ability using a nested table with a
union field.

* fix: Uncommented generate code command
2022-10-26 14:56:52 -07:00
Derek Bailey
5a48b0d7d6 release.yml: Typo 2022-10-26 00:40:43 -07:00
Derek Bailey
ce307556fb release.yml: Remove npm ci
This command [was suggested](https://docs.github.com/en/actions/publishing-packages/publishing-nodejs-packages#publishing-packages-to-the-npm-registry) in the github docs, but not in our release steps.
2022-10-26 00:35:11 -07:00
Derek Bailey
cb616e27cb Create release.yml (#7605)
Create a new `release.yml` for defining automatic publishing to package managers on releases.

Adds the NPM publishing steps as it is the most straightforward.
2022-10-26 00:30:16 -07:00
Derek Bailey
a54ca1e759 FlatBuffers Version 22.10.25 (#7604) 2022-10-26 00:03:49 -07:00
ArnaudD-FR
5b3fadcc16 [vector] Allow to iterate with mutables (#7586)
Co-authored-by: ArnaudD-FR <arnaud.desmier@gmail.com>
Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-10-21 12:10:18 -07:00
Dan Lapid
872a497464 [Nim] Bfbs Nim Generator (#7534)
* Bfbs Nim Generator

* Remove commented out tests

* add missing line to idl.h

* Commit python reflection changes

* Commit python reflection changes and move tests

* Remove default string addition

* Move tests to python file

* Fix element size check when element is table

* remove whitespace changes

* add element_type docs and commit further to namer and remove kkeep

* Bfbs Nim Generator

* Remove commented out tests

* add missing line to idl.h

* Commit python reflection changes

* Commit python reflection changes and move tests

* Remove default string addition

* Move tests to python file

* Fix element size check when element is table

* remove whitespace changes

* add element_type docs and commit further to namer and remove kkeep

* remove unused variables

* added tests to ci

* added tests to ci

* fixes

* Added reflection type Field, Variable to namer

* Moved reflection namer impl to bfbsnamer

* Remove whitespace at end of line

* Added nim to generated code

* Revert whitespace removal

Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-10-21 14:30:04 -04:00
Dominic Battre
e301702964 Make type conversions explicit. (#7595)
As Java does not support unsigned integer types, the value types
are "rounded up" (an uint32 is represented as a long) but persisted
correctly (an uint32 is persisted as 4 bytes).

This CL makes a cast operation explicit so that the compiler
does not throw warning messages.

Co-authored-by: Dominic Battre <battre@chromium.org>
Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-10-21 09:09:28 -07:00
Dominic Battre
f7b734438d Fix LongEnum definitions (#7596)
The MyGame/Example/LongEnum.java class did not compile because
Java expects an "L" suffix for literals of type long.

This CL fixes the code generation to include such a suffix.

Co-authored-by: Dominic Battre <battre@chromium.org>
2022-10-20 18:15:00 -07:00
Dan Lapid
5792623df4 Rust fix compilation for no_std targets #2 (#7553)
* Fix nightly no_std

* Fix nightly no_std
2022-10-19 09:14:41 -04:00
Casper
0edb275285 Update Rust version (#7574)
Co-authored-by: Casper Neo <cneo@google.com>
2022-10-18 20:37:12 +00:00
Dominic Battre
acc6a20d39 tests/test.cpp contains a couple of tests that are only executed (#7571)
on a subset of platforms. The test calls are guarded via #ifndef
FLATBUFFERS_NO_FILE_TEST.

Embedders of flatbuffers that rely on -Werror,-Wunused-function
compiler flags (like chromium) complain about the exsitence of these
tests in the anonymous namespace.

This CL guards the test definitions as well (not just the test
calls).

Co-authored-by: Dominic Battre <battre@chromium.org>
Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-10-18 12:37:06 -07:00
Casper
04cd037ba2 Fix #7580 by documenting union schema evolution rules (#7585)
Co-authored-by: Casper Neo <cneo@google.com>
2022-10-17 17:49:28 -04:00
Casper
e1c5db988a Turn on clippy for Rust and fix lints for non-generated code (#7575)
Co-authored-by: Casper Neo <cneo@google.com>
2022-10-10 21:26:35 -04:00
Piotr Dziwiński
b80142b901 Update documentation to mention enum value attributes (#7570) 2022-10-08 19:52:38 -04:00
Piotr Dziwiński
54418f371b Add support for metadata attributes for enum values (#7567) (#7568)
* Add support for metadata attributes for enum values (#7567)

* Fix path lookup in flatc test

* Try a fix for Windows paths

* Convert path to string to fix Windows error
2022-10-06 20:18:00 -04:00
Derek Bailey
c92e78a9f8 FlatBuffers Version 22.9.29 (#7557) 2022-09-29 22:12:07 -07:00
Björn Harrtell
d243b904cc [TS] Make strict compliant and improve typings (#7549)
* [TS] Make strict compliant and improve typings

* clang-format

* Code gen harmonize

Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-09-29 15:03:35 -07:00
Raphael Taylor-Davies
374f8fb5fb Rust soundness fixes (#7518)
* Rust soundness fixes

* Second pass

* Make init_from_table unsafe

* Remove SafeSliceAccess

* Clippy

* Remove create_vector_of_strings

* More clippy

* Remove deprecated root type accessors

* More soundness fixes

* Fix EndianScalar for bool

* Add TriviallyTransmutable

* Add debug assertions

* Review comments

* Review feedback
2022-09-29 09:58:49 -04:00
mustiikhalil
dadbff5714 Moves swift package to root of repository so it can be used directly … (#7548)
* Moves swift package to root of repository so it can be used directly from the main repo

Fixing paths for swift directory

* Update swift readme
2022-09-27 14:32:05 -07:00
Derek Bailey
76ddae006f FlatBuffers Version 22.9.24 (#7547) 2022-09-27 11:55:25 -07:00
Mark Pauley
cfe157ec56 Emit internal enums when swift_implementation_only (#7545)
- Copy the same pattern as structs and tables
- Fixes google#7542
2022-09-24 20:15:39 +02:00
Joshua Smith
413115858c [Python] Python fixed size array (#7529)
* feat: Added support for fixed sized arrays to python

Problem:
We encountered that using fixed arrays from C++ to python that python would
not read those arrays correctly due to no size information being encoded in the byte
array itself.

Fix:
Encode the sizes within the generated python file during code generation.
Specfically we add GetArrayAsNumpy to the python version of table, which takes as input
the length of the vector. When generating the python message files we include this length
from the VectorType().fixed_length.

* fix: added digit support for camel case to snake case conversion

Problem:
When including a number in the message name we would encounter cases where SnakeCase would
not add the appropirate breaks. e.g. Int32Stamped -> int_32stamped rather than int_32_stamped.

Fix:
To fix this we can add the condition that we check if the current character is not lower and
not a digit, that we check if the previous character was a lower or digit. If it was a lower
or digit then we add the break.

* fix: Array support for structures

Problem:
The python generated code for handling non-struct and struct vectors
and arrays was inconsistent. The calls to populate the obj api was
creating incorrect code.

Solution:
To fix this the VectorOfStruct and VectorOfNonStruct was rewritten
to handle array cases and bring the two methods in line which each
other.

Testing:
PythonTesting.sh now correctly runs and generates the code for
array_test.fbs.
Minor modifications were done on the test to use the new index
accessor for struct arrays and the script correctly sources the
location of the python code.

* chore: clang format changes

* Added code generated by scripts/generate_code. Modified GetArrayOfNonStruct slightly
to allow for function overloading allowing the user to get a single element of an array
or the whole array.

* Added new_line parameter to OffsetPrefix to allow optional new lines to be added.
This allows us to use the GenIndents method that automatically adds new lines instead.

* Reupload of generated code from the scripts/generate_code.py

* Removed new line in GetVectorAsNumpy.

* Updated Array lengths to use Length methods where possible. Added fallthrough for GenTypePointer. Added digit check to CamelToSnake method. Added and modified tests for ToSnakeCase and CamelToSnake.

* Added range check on the getter methods for vector and array types. Renamed == as is for python
2022-09-22 11:08:09 -07:00
Yun Peng
88046190ee Upgrade grpc to 1.49.0 and make sure it builds (#7538)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-09-21 12:53:03 -07:00
Denis Blank
72aa85a759 [C++] Rare bad buffer content alignment if sizeof(T) != alignof(T) (#7520)
* [C++] Add a failing unit test for #7516 (Rare bad buffer content alignment if sizeof(T) != alignof(T))

* [C++] Fix final buffer alignment when using an array of structs
* A struct can have an arbitrary size and therefore sizeof(struct) == alignof(struct)
  does not hold anymore as for value primitives.
* This patch fixes this by introducing alignment parameters to various
  CreateVector*/StartVector calls.
* Closes #7516
2022-09-21 11:05:05 -07:00
Dorochi
bfceebb7fb Fix conform (#7532)
* Fix conform;
Make sure the command fails when tail fields are removed;

* Fix last commit according to dbaileychess' comment
2022-09-14 21:45:40 -07:00
Derek Bailey
bc44fad352 UnPackTo disable merge by default (#7527)
* UnPackTo disable merge by default

* avoid double free in test

* remove merge parameter

* remove shrink to fit
2022-09-13 22:00:01 -07:00
Björn Harrtell
4fca4dc60c [TS/JS] Move TS tests to dedicated folder and deps upgrade (#7508)
* Move TS tests to dedicated folder and deps upgrade

* Attempt to fix generate_code

* Fix dir on CI

* Add js extension

* Fix missing extension

* Harmonize with test gen

* Unexplained code gen change

* Restore yarn.lock

* Naive attempt to fix bazel stuff

* Pin @bazel/typescript to 5.2.0

* Attempt to fix bazel

* More tweak

* Upgrade deps

* Tweak?

* Fix path

* Fix test package

Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-09-12 20:03:23 -07:00
dependabot[bot]
036032373b Bump junit from 4.13 to 4.13.1 in /java (#7526)
Bumps [junit](https://github.com/junit-team/junit4) from 4.13 to 4.13.1.
- [Release notes](https://github.com/junit-team/junit4/releases)
- [Changelog](https://github.com/junit-team/junit4/blob/main/doc/ReleaseNotes4.13.1.md)
- [Commits](https://github.com/junit-team/junit4/compare/r4.13...r4.13.1)

---
updated-dependencies:
- dependency-name: junit:junit
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-09-11 19:56:51 -07:00
Nick
89dfb43f3b Replace bash JavaTest.sh with mvn test (#7500)
* Start of mvn-ification of the test

* move to right locations

* Update the IO done in the test to read from resources / write to temp folders

* Add github workflow attempt to mvn test it instead of JavaTest.sh

* Pin the Kotlin benchmark's symlink for /java to the right location

* Inline equality assertions and format JavaTest.java

* fix android gradle source directory

Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-09-11 17:46:46 -07:00
Derek Bailey
c49aff4b6f enabled cpp17 tests in CI (#7524) 2022-09-11 16:08:07 -07:00
Derek Bailey
56e60223c3 prevent force_align attribute on enums (#7523) 2022-09-10 13:41:58 -07:00
Derek Bailey
89b1f5aa1b remove travis config (#7522)
* remove travis config

* remove more travis and appveyor stuff

* remove appveyor specific things
2022-09-10 12:36:51 -07:00
Paulo Pinheiro
b901598233 [Java][Flexbuffers] Add API to add nullables into the buffer. (#7521)
Fix #7517
2022-09-10 09:13:01 -07:00
Derek Bailey
8cdc6a2885 Install BuildFlatBuffers.cmake (#7519) 2022-09-10 00:30:47 -07:00
mustiikhalil
a67e35aff9 Moves all of the swift test code into tests/swift (#7509)
Fixes failing tests by regenerating test cases
2022-09-09 22:35:42 -07:00
Derek Bailey
f124e41ae6 Updated Readme
Added links to runtime packages for variety of languages.
2022-09-03 08:05:36 -07:00
Paulo Pinheiro
4c954181cd [Java][FlexBuffers] throwing exception for untyped fixed vectors (#7507)
Untyped fixed vectors are not supported in FlexBuffers. There
was an assert to check for it, but on java, asserts are optional. This
change converts the assertion into a runtime exception.

Fixes #7358

Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-09-01 22:04:18 -07:00
Paulo Pinheiro
7f7547737e [Android] Remove maven dependency of flatbuffers and use source folder (#7503) 2022-09-01 14:58:25 -07:00
mustiikhalil
a79d61ea85 Fixes issue with cocoapods failing to be published because of docc (#7505)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-09-01 11:44:13 -07:00
Chris Langhans
d465b39c3e [CMake]: fix breaking find_package change (#7499) (#7502)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-09-01 10:28:59 -07:00
Derek Bailey
c5a609dc20 [C#] Prepares for official Nuget release (#7496)
* Define nuget package

* C# Switch to Google.FlatBuffers namespace

* Add Source Link for nuget package

* Add Strong Name signing of Google.FlatBuffers
2022-09-01 10:17:34 -07:00
Ivan Zakharchanka
5634dc3d0d [ISSUE-6268] returns NaN insteadof nan (#7498)
* returns NaN insteadof nan

* clang-format-git
2022-08-31 16:22:17 -07:00
mustiikhalil
37e37b8cad Updates cocoapods version (#7497) 2022-08-31 10:20:11 -07:00
Derek Bailey
8fd4534fbe update android multidex setting (#7495) 2022-08-30 14:32:16 -07:00
Derek Bailey
d5427da52f Disable Android Build (#7494) 2022-08-29 22:16:04 -07:00
Derek Bailey
06c5c7ed0b FlatBuffers Version 2.0.8 (#7492) 2022-08-29 20:43:36 -07:00
Derek Bailey
b190ce11b0 Verifier Refinements (#7490) 2022-08-29 19:21:42 -07:00
Casper
bf5d23230a Namer applied to Typescript generator (#7488)
* Namer applied to Typescript generator

* fixes

* More fixes

Co-authored-by: Casper Neo <cneo@google.com>
Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-08-29 16:44:35 -07:00
Björn Harrtell
ce382d6dd3 [TS/JS] Add rollup and config to generate iife flatbuffers bundle (#7449)
* Add rollup and config to generate iife flatbuffers bundle

* Atempt to use yarn and add deps

Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-08-29 16:37:43 -07:00
Casper
41d9add7ef C++: Add option to skip verifying nested flatbuffers (#7489)
* C++: Add option to skip verifying nested flatbuffers

Additionally, add an options struct to the verifier for those
who prefer designated initializers to default arguments. The former
constructor is defined in terms of the latter because in old c++,
having default values for members removes list initialization, making
defining constructors in the other way a lot more challenging to write.

* fixes

* fmt

* formatting, and remove an argument

* fix

Co-authored-by: Casper Neo <cneo@google.com>
Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-08-29 16:25:57 -07:00
sssooonnnggg
6a87427540 [C++] support native_inline attribute for vector of tables (#7479) 2022-08-29 12:48:10 -07:00
Derek Bailey
694add668b Refactor test.cpp (#7487)
* Add timing command to cmakelist

* Start to split test.cpp. Move flexbuffers tests

* Move monster related tests to own file

* Move parser related tests to own file

* Move json related tests to own file

* Move proto related tests to own file

* moved more functions to parser test

* moved more functions to parser test2

* move monster extra tests to monster test

* move evolution tests to own file

* move reflection tests to own file

* move util tests to own file

* rehomed various tests

* move optional scalars test to own file:

* rehome more tests

* move fuzz tests. Got rid of global test_data_path

* fixes for CI failures

* add bazel files
2022-08-28 16:54:58 -07:00
Derek Bailey
7edf8c9084 Update scorecard to 1.1.2 2022-08-26 14:40:36 -07:00
Derek Bailey
b86387442e Fix typos (#7483) 2022-08-26 14:35:21 -07:00
Derek Bailey
e2eb5ee670 Include <array> head in stl_emulation.h (#7480)
* Add C++ standard builds for windows CI

* Allow C++std to be specified in cmake

* Include <array> in stl_emulation

* Add linux std CI builds
2022-08-26 00:22:27 -07:00
Axel Sommerfeldt
994502b6dd Version number in file package.json updated to 2.0.7 (#7476)
Co-authored-by: Axel Sommerfeldt <axel.sommerfeldt@gmail.com>
Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-08-25 20:40:50 -07:00
sssooonnnggg
fa41e83679 [C++] Fixed crash when copying table with empty shared strings (#7477) 2022-08-25 16:50:17 -07:00
Derek Bailey
799cc8f7b9 Use type traits for specialization (#7475) 2022-08-24 12:16:44 -07:00
Derek Bailey
b7eb441470 Disable RTTI and rework use in idl_gen_ts.cpp (#7474) 2022-08-24 10:36:11 -07:00
Axel Sommerfeldt
8d01c5859c CMake project version detection made more robust (#7473)
This fixes two problems:
1. The project could be build when using own tags which does not follow the pattern v<major>.<minor>.<patch>.
2. The case "tag points to the commit" will be handled correctly by setting VERSION_COMMIT to 0.

This commit resolves https://github.com/google/flatbuffers/issues/7472

Co-authored-by: Axel Sommerfeldt <axel.sommerfeldt@gmail.com>
2022-08-24 09:28:52 -07:00
Derek Bailey
237e8b71fe Moved compiler warnings around (#7471) 2022-08-23 23:23:24 -07:00
Derek Bailey
eeb8fd60d5 Include builder.addOffset for vector of structs (#7470) 2022-08-23 23:17:35 -07:00
Derek Bailey
fef2ffc4d0 Use schema include name for keep-prefix (#7469) 2022-08-23 21:29:17 -07:00
Derek Bailey
8367664f15 Flatbuffers Version 2.0.7 (#7462) 2022-08-22 21:42:15 -07:00
Derek Bailey
d6f06c33f7 Reworked keep prefix (#7456)
* reworked keep prefix

* checking in missing schema

* fix flatc path for build scripts
2022-08-22 18:59:24 -07:00
Xùdōng Yáng
627e8bf364 update grpc version (#7457)
* update grpc version

this in turn updates the upb version, which fixes Flatbuffers' failure in Bazel CI: https://buildkite.com/bazel/bazel-at-head-plus-downstream/builds/2586#0182a995-a528-4e87-90a0-1604a5e9f7eb

* also update rules_go version

* the new rules_go actually needs a version

* grpc_extra_deps() also registers go toolchains

* make buildifier happy

* address review comments
2022-08-22 16:53:28 -07:00
Derek Bailey
883c42b7db disabling unpackto optimization (#7459) 2022-08-18 20:51:18 -07:00
Derek Bailey
7aae0af305 Remove old GRPC bash script and convert to python3 (#7454)
* Remove old GRPC bash script and convert to python3

* updated checking gRPC script to python3
2022-08-16 23:44:50 -07:00
Paul Harris
b057aa917f Grouped anonymous namespaces together, (#7455)
A follow-up PR to #7212
2022-08-16 22:45:21 -07:00
Derek Bailey
f1b26ff7fb Change to GetTypeName (#7453) 2022-08-16 20:32:53 -07:00
laurentsimon
9610a666b1 Generate SLSA signatures for Released zip files (#7450)
* update

* update

* update

* update

* update

* update

* update
2022-08-16 16:30:37 -07:00
Paulo Pinheiro
1e0f75a647 [WIP] speedup (#7452) 2022-08-16 13:47:08 -07:00
Derek Bailey
82b75407a3 Wrap types in namespace for --ts-flat-files and --gen-all (#7451)
* Wrap types in namespace for --ts-flat-files and --gen-all

* Fixes for escaping object types

* Added to generate_code
2022-08-16 12:52:26 -07:00
Paul Harris
f7c511957f Audit and fixups for GCC and Clang (#7212)
Added (for compiler versions that support it):
-Wmissing-declarations
-Wzero-as-null-pointer-constant

Then, fixes to problems identified by the extra warnings
Tested only on GCC 9.4.0

Adjusted the CPP code generator to output nullptr where appropriate,
to satisfy -Wzero-as-null-pointer-constant

Added a lot of 'static' declarations in front of functions,
to satisfy -Wmissing-declarations,
and wrap static function defs in anonymous namespaces.

There are advantages to both anonymous namespaces and static,
it seems that marking a function as static will not publish the name in
the symbol table at all, thus giving the linker less work to do.
2022-08-16 10:48:41 -07:00
Derek Bailey
a66de58af9 Partial support for --ts-flat-files and --gen-all (#7446)
* Partial support for --ts-flat-files and --gen-all

* Add generated code changes

* remove some debugging code left over

* missed grpc files
2022-08-15 16:11:45 -07:00
Paulo Pinheiro
a3508f36d5 [Kotlin] Make sure namespace path exist for code generation (#7357)
With a change introduce in 385dda5c3785ed8d6a35868bc169f07e40e889087fd2edc66,
flatc was not able to emit code for Kotlin if a namespace is specified
and the folders do not exist. The fix create folders if neded.

Additional changes are introduced in gradle files to bring more visibility
to the error messages.

Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-08-15 10:13:27 -07:00
Mirko Bonadei
137fec7164 Stop using __has_trivial_copy on recent clang versions. (#7443)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-08-15 09:49:59 -07:00
Derek Bailey
214125e417 [C#] Rework how sorted vectors are looked up (#7441) 2022-08-15 09:33:07 -07:00
Derek Bailey
44a7dc9995 Define minimum buffer size (#7440)
* add check for zero sized buffers

* Define minimum flatbuffer size
2022-08-14 12:40:57 -07:00
Stefan F
3cc2daa78f make_span overloads for pointer to vector (#7374) (#7435)
* make_span overloads for pointer to vector (#7374)

* findings from the review

Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-08-14 12:21:55 -07:00
Derek Bailey
fa1174aa7b [TypeScript] Fix namespaceless schema generation (#7432)
* Add tests for ts flatc

* fix typescript generation of namespaceless file

* Add typescript genereated code from generate_code.py

* Support multiple module flatc testing
2022-08-14 11:34:19 -07:00
Derek Bailey
83d4e2a100 Add checks to verifier (#7438) 2022-08-13 23:44:13 -07:00
Maxim Zaks
8a09f3fb0b Fix FlexBuffers JS/TS bug https://github.com/google/flatbuffers/issues/6934 (#7434)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-08-13 18:29:28 -07:00
Derek Bailey
9dbe819efd Add flatc python tests to CI (#7437) 2022-08-13 17:30:51 -07:00
Derek Bailey
67c4149588 Update TypeScriptTest.py to work better cross platform (#7436) 2022-08-13 17:01:32 -07:00
Derek Bailey
8b8c7dbdfc Update gitingore to reflect name change (#7431) 2022-08-12 21:02:24 -07:00
Derek Bailey
2ee20a5f3d Remove auto including locale functions (#7430) 2022-08-12 15:23:46 -07:00
sssooonnnggg
4be605604e [C++] Set StructDef::has_key property when deserializing from binary schema (#7386) (#7428) 2022-08-12 09:27:17 -07:00
Marcel Krüger
fc5d86f1e7 [C++] Make template parameter in stl_emulation.h more explicit to avoid conflicts with cpprestsdk U macro (#7424)
* [C++] Rename template parameter U in make_span of stl_emulation.h

CPPRESTSDK defines a U macro therefore, calls to U() are problematic.
Rename U to W to avoid conflict.

* [C++] Make typenames of span_convertable and make_span more expressive

Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-08-10 13:22:08 -07:00
Yashasvi Chaurasia
9dce287adb Issue#6959 :Updated Automatically generated rust files. (#7425)
* test

* only rust files

* updated idl_gen_rust.cpp
2022-08-10 09:15:35 -04:00
sssooonnnggg
7798be3bb6 avoid zero-as-null-pointer warning (#7423)
Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-08-08 21:32:13 -07:00
Derek Bailey
966362e074 [C++] Vector of Tables equality (#7415)
* Vector of Tables equality

* support nullptr and fix for not being able to use auto in lambda

* use different std::equal overload

* use flatbuffers::unique_ptr

* go back to auto and clang-format fix
2022-08-08 21:22:57 -07:00
Andrei Burdulescu
a89c279ed6 [golang] Perform keyword escaping after case conversion (#7421)
Change config.escape_keywords to AfterConvertingCase.

It avoids unecessay escaping since the generated native
structs have fields starting with a uppercase letter
and Go's keywords start with lowercase letters.

Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-08-08 20:46:35 -07:00
Derek Bailey
a212b3c036 Turn of fail fast for C++ CI
Prevent failing fast if one of the two c++ compilers fail
2022-08-08 19:12:18 -07:00
Derek Bailey
9230f600d7 Remove stringop-overflow from error (#7422) 2022-08-08 19:08:32 -07:00
Andrei Burdulescu
c793621567 [golang] Add support for text parsing with json struct tags (#7353)
* [golang] Add support for text parsing with json struct tags

Add struct tags to Go native structs generated when object API is used.

This allows to use the same JSON file as for C++ text
parsing(i.e. snake_case vs CamelCase) and thus enabling text parsing
for Go(when using object API).

* [golang] Add test for text parsing

Added small test to check and demonstrate text parsing in Go.
Also, ran clang-format on cpp file changes.
2022-08-08 11:30:06 -07:00
Derek Bailey
ee2ced236d Moved TypeScriptTests to python script (#7411)
* Moved TypeScriptTests to python script

* fixed CI issue with out-dated generated file

* Build flatc for TS CI

* reverting yarn.lock
2022-08-07 11:42:02 -07:00
Aman Priyadarshi
468c00a3fe Rebased: grpc/compiler: Respect filename suffix and extension during code generation (#7414)
* grpc/compiler: Respect filename suffix and extension during code generation

grpc compiler is not respecting filename suffix and extension passed to
flatc CLI. This causes compiler to spit out incorrect code, which then
cannot be compiled without modification.

Following patch fixes the problem.

Note, I ended up removing some code introduced #6954 ("Have grpc include
file with correct filename-suffix given to flatc") in favour of keeping
sanity of the generator code.

Signed-off-by: Aman Priyadarshi <aman.eureka@gmail.com>

* tests: Add filename-suffix and filename-ext test files

* Test 1: Filename extension changed to "hpp".
* Test 2: Filename suffix changed to "_suffix".
* Test 3: Filename extension changed to "hpp" and suffix changed to "_suffix"

Signed-off-by: Aman Priyadarshi <aman.eureka@gmail.com>
2022-08-07 11:32:53 -07:00
Derek Bailey
47c757f714 Add tests for flatc (#7405) 2022-08-06 21:11:03 -07:00
Derek Bailey
9a5ff89003 Add FLATBUFFERS_STRICT_MODE (#7408) 2022-08-06 21:06:14 -07:00
Björn Harrtell
950444a343 [TS] Use TextEncoder and TextDecoder (#7400)
* [TS] Use TextEncoder

TextEncoder is well supported these days, see https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder#browser_compatibility.

* Reuse instance

* Also use TextDecoder

* Forgot to add text_decoder_ member

Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-08-06 22:00:30 +00:00
Ivan Shynkarenka
30d76198c7 Compilation issue msys2 #7399 (#7409)
* Compilation issue msys2 #7399

* Compilation issue msys2 #7399
2022-08-06 14:56:22 -07:00
Derek Bailey
cce3a66f0d Delete .travis directory
We don't use travis anymore.
2022-08-06 12:30:13 -07:00
Derek Bailey
8d1cc6ac7d Revert "Compilation issue msys2 (#7403)" (#7407)
This reverts commit da702cfd8f.
2022-08-06 10:19:50 -07:00
Derek Bailey
5b207639a1 Update readme.md
Add scorecard badge via: https://github.com/ossf/scorecard-action#view-results
2022-08-05 23:41:06 -07:00
Derek Bailey
359e0f9d66 Revert "grpc/compiler: Respect filename suffix and extension during code generation (#7343)" (#7406)
This reverts commit 97e89c5acd.
2022-08-05 23:20:33 -07:00
Derek Bailey
ebbed05137 Delete cpp-linter.yml
Linter was not that useful, so removing it.
2022-08-05 22:56:00 -07:00
Chris Langhans
aa395e5a59 (#7323) Rename CMake files according to project name (#7378)
* CMake find_package fixes (#7323)

Rename FlatbuffersConfigVersion.cmake to match CMake project name

* CMake find_package fixes (#7323)

Rename FlatBuffersTargets to match CMake project name
2022-08-05 22:19:17 -07:00
SF-Zhou
32328075d8 Fix error msg format when generate GRPC failed (#7350) 2022-08-05 22:12:15 -07:00
Aman Priyadarshi
97e89c5acd grpc/compiler: Respect filename suffix and extension during code generation (#7343)
* grpc/compiler: Respect filename suffix and extension during code generation

grpc compiler is not respecting filename suffix and extension passed to
flatc CLI. This causes compiler to spit out incorrect code, which then
cannot be compiled without modification.

Following patch fixes the problem.

Note, I ended up removing some code introduced #6954 ("Have grpc include
file with correct filename-suffix given to flatc") in favour of keeping
sanity of the generator code.

Signed-off-by: Aman Priyadarshi <aman.eureka@gmail.com>

* tests: Add filename-suffix and filename-ext test files

* Test 1: Filename extension changed to "hpp".
* Test 2: Filename suffix changed to "_suffix".
* Test 3: Filename extension changed to "hpp" and suffix changed to "_suffix"

Signed-off-by: Aman Priyadarshi <aman.eureka@gmail.com>
2022-08-05 22:11:45 -07:00
06393993
5f6672be44 Fix Clang-Cl compile on Windows (#7308)
Introduce a MSVC_LIKE variable in the CMake scripts, set that variable to
true only if the compiler is either MSVC or tries to emulate the MSVC
command line, and test that variable when setting compiler arguments.

Tested with cmake .. -G Ninja -DCMAKE_C_COMPILER:PATH="clang-cl.exe" -DCMAKE_CXX_COMPILER:PATH="clang-cl.exe" -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_BUILD_CPP17=ON

Co-authored-by: Kaiyi Li <kaiyili@google.com>
2022-08-05 22:08:36 -07:00
James Kuszmaul
28e858c855 [TS/Bazel] Minor improvements to typescript.bzl (#7300)
* Move reflection_ts_fbs into a separate directory (#7342)

Right now, reflection_ts_fbs target is in reflection/BUILD.bazel.

This is not ideal because reflection:reflection_fbs_schema is referenced
from :flatc in the root. Thus, for any Bazel projects that want to
include flatbuffers, they need to include npm / yarn_install and nodejs
support all because reflection/BUILD.bazel loads typescript.bzl and that
requires all TypeScript things.

This PR separated that target into a different subdirectory, freeing
root BUILD.bazel from that dependency.

* Minor improvements to typescript.bzl

* Uses @...// dependencies so that flatbuffers can actually
  be used as an external repo (had forgotten to upstream this earlier).
* Allows using flatbuffer_ts_library to generate reflection schemas
  in the same way that flatbuffer_cc_library does (but default it
  to off to avoid behavioral changes).
* Pass through a package_name attribute to flatbuffer_ts_library to
  allow non-relative imports of generated typescript code.

Co-authored-by: Liu Liu <i@liuliu.me>
2022-08-05 22:04:05 -07:00
sssooonnnggg
987bebe678 [TS] fix incorrect reverse when writting array of structs (#7271) 2022-08-05 22:00:16 -07:00
Wouter van Oortmerssen
ec0129369c Fix FlexBuffers Verifier tracking vectors reuse at wrong offset
See test for an example.
Found in: https://github.com/aardappel/lobster/pull/193
2022-08-05 10:45:01 -07:00
Atil Kurtulmus
50dd385b30 Add missing const (#7401) 2022-08-05 11:11:00 -04:00
Ivan Shynkarenka
da702cfd8f Compilation issue msys2 (#7403)
* Compilation issue msys2 #7399

* Fix flatbuffers compilation issue
2022-08-05 10:10:58 -04:00
Derek Bailey
6e2791640e keep-prefix keeps relative pathing (#7394) 2022-07-26 15:11:54 -07:00
godcong
52fce5e532 fix(#7360): grpc used deprecated functions (#7361) 2022-07-26 15:10:13 -07:00
Yasser Shalabi
b7f13cd8e8 cpp_generator: comment out unused parameter to avoid warnings (#7381)
Presently flatc generates a placeholder for the unused synchronous varient of client-side streaming gRPCs which includes the name of an unused parameter in the method.

To avoid warnings, comment out the parameter name (in a manner similar to other gRPCS).
2022-07-26 15:05:01 -07:00
Derek Bailey
e42985e5aa Updated Newtonsoft.Json to 13.0.1 (#7393) 2022-07-26 13:22:18 -07:00
Ian Hickson
0a80646371 Fix references to LICENSE file (#7377)
* Fix references to LICENSE file

This was broken by https://github.com/google/flatbuffers/pull/7073

* Update flat_buffers_test.dart
2022-07-07 16:06:19 -07:00
Will Hughes
b9eea76a86 [Dart] Implement putBool to fix errors when serializing structs with bools (#7359)
* [Dart] Implement putBool to fix errors when serializing structs with bools

* Add tests
2022-06-28 11:16:47 -04:00
dependabot[bot]
1b90300150 Bump Newtonsoft.Json from 12.0.3 to 13.0.1 in /tests/FlatBuffers.Test (#7363)
Bumps [Newtonsoft.Json](https://github.com/JamesNK/Newtonsoft.Json) from 12.0.3 to 13.0.1.
- [Release notes](https://github.com/JamesNK/Newtonsoft.Json/releases)
- [Commits](https://github.com/JamesNK/Newtonsoft.Json/compare/12.0.3...13.0.1)

---
updated-dependencies:
- dependency-name: Newtonsoft.Json
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-06-23 15:03:07 -04:00
Caleb Zulawski
83a43fc797 Reenable optional json (#7352)
* Revert "Revert "Implement optional scalars for JSON (#7322)" (#7351)"

This reverts commit 9a1913a87a.

* Add optional scalars json to bazel

Co-authored-by: Caleb Zulawski <caleb.zulawski@caci.com>
2022-06-16 09:26:44 -07:00
Derek Bailey
5f01376027 Only include direct included filed (#7348) 2022-06-15 12:10:39 -07:00
Derek Bailey
9a1913a87a Revert "Implement optional scalars for JSON (#7322)" (#7351)
This reverts commit a18ea40d6a.
2022-06-15 00:32:28 -07:00
Derek Bailey
b4647beb8f Revert "Move reflection_ts_fbs into a separate directory (#7342)" (#7349)
This reverts commit 090caa2809.
2022-06-14 20:58:00 -07:00
Derek Bailey
d6060977ad Remove asserting in verifier for flattests 2022-06-14 20:53:28 -07:00
Derek Bailey
987aa5b5ee move -Wextra-semi to GCC 8.0+ 2022-06-14 16:32:10 -07:00
James Kuszmaul
42acdb63c3 [TS] Don't generate self-imports with --ts-flat-file (#7340)
The logic to manage generating typescript in a single file was
generating self imports and unused local names, which triggered some
linters.

This resolves #7191
2022-06-14 15:51:12 -07:00
Timo Sturm
0cc1aeb8ca [golang] Create missing namespace directory structure (#7324) (#7325) 2022-06-14 15:50:05 -07:00
Paulo Pinheiro
ba6c671705 [Kotlin] Remove download benchmark files dependency (#7314)
There was a step in the compilation process where benchmark data is
downloaded before starting the kotlin compilation process.

Since we are not running benchmark on CI anymore, we remove the
dependency. To run benchmarks the download task needs to be executed
manually.
2022-06-14 15:49:42 -07:00
Derek Bailey
d2f33fc454 Disable Android on Linux CI build 2022-06-14 15:46:48 -07:00
sssooonnnggg
0d1b72cbc2 [TS] fix ts import path issue (#7298) 2022-06-14 15:25:35 -07:00
Koya IWAMURA
9fce2fbf2a replace io/ioutil to os (#7281) 2022-06-14 15:10:57 -07:00
Caleb Zulawski
a18ea40d6a Implement optional scalars for JSON (#7322)
* Implement optional scalars for JSON

* Add optional scalars JSON test

* Extend JSON optional scalars test to test without defaults

* Fix optional scalars in JSON for binary schema

Co-authored-by: Caleb Zulawski <caleb.zulawski@caci.com>
2022-06-14 18:00:24 -04:00
Liu Liu
090caa2809 Move reflection_ts_fbs into a separate directory (#7342)
Right now, reflection_ts_fbs target is in reflection/BUILD.bazel.

This is not ideal because reflection:reflection_fbs_schema is referenced
from :flatc in the root. Thus, for any Bazel projects that want to
include flatbuffers, they need to include npm / yarn_install and nodejs
support all because reflection/BUILD.bazel loads typescript.bzl and that
requires all TypeScript things.

This PR separated that target into a different subdirectory, freeing
root BUILD.bazel from that dependency.
2022-06-13 09:36:52 -04:00
Caleb Zulawski
49e1ea3335 Implement optional scalars for Python (#7318)
* Implement optional scalars for Python

* Use == for integer comparison, remove empty line

* Fix optional type hint

Co-authored-by: Caleb Zulawski <caleb.zulawski@caci.com>
2022-06-13 09:16:00 -04:00
mustiikhalil
11a1988705 Started implementation for private flags in rust (#7269)
Adds flag to the cpp to fix bad annotations in all the languages

Addresses comments to the PR, and fixes logic for leaking annotations
2022-06-05 23:04:05 +02:00
mustiikhalil
967df08b1d Adds full supposed for Wasm in the swift lib (#7328)
Adds tests for wasm module & github action
2022-05-29 20:56:33 +02:00
Casper
9aa08a429e Use keep case for Rust union discriminant type. (#7321)
Fixes #7320.

I realize that Rust doesn't really follow the Namer convention, since
it uses Field case for methods... that's a future problem.

Co-authored-by: Casper Neo <cneo@google.com>
2022-05-23 15:53:00 -04:00
Bart van der Werf
9e8c758f54 Add explicit return types to lobster generated code (#7312)
* Add explicit return types to lobster generated code

* Add support for optional fields.

Convert to bool explicitly from int8 to match type signature
Fix whitespace
2022-05-23 10:50:01 -07:00
Björn Harrtell
74a25536be Add size check to fix out of bounds read risk (#7304) 2022-05-13 15:15:00 -07:00
Brian Silverman
12917af8a2 Update Rust docs page (#7296)
I think these changes reflect the current state, but I found it hard to
track the state of some of the planned work. Hence why it'd be good to
have it documented :)

I also expanded some sections that I found misleading, as somebody
familiar with Rust and FlatBuffers separately. Parts of these pages seem
to be aimed at people familiar with FlatBuffers (ie via the other
documentation pages) but not each language, which I'm trying to
preserve. However, Rust does some things differently, and as somebody
with expectations about how typical Rust APIs work the discussion of
threading made me wonder what was different.
2022-05-12 10:02:14 -07:00
mr-swifter
1ea2472f7a [swift] add had<ArrayName> property for arrays to check presence in a message (#7280) 2022-05-11 15:35:53 +02:00
pkasting
0fe13cb28c Remove span ConstIterator/cbegin()/cend(). (#7295)
std::span lacks these; make  the flatbuffers STL emulation and tests
match.  This fixes a compile error in C++20 mode when using std::span.

Bug: chromium:1284275
2022-05-10 13:53:38 -07:00
Casper
385dddc66a Namerkot (#7245)
* Namer for Kotlin

* delete unread cur_name_space_ and apply Namer to filename

Co-authored-by: Casper Neo <cneo@google.com>
2022-04-26 21:54:49 -04:00
Bogdan Opanchuk
750dde7669 Make flatc generate Rust files not requiring std (#7273)
* Set an explicit 2018 edition for Rust tests

* Replace all `std` usage with `core` and `alloc` in Rust code generator

* Update the generated files

* Make Rust tests actually use no_std when the corresponding feature is enabled
2022-04-26 21:40:03 -04:00
Keith Smiley
9917a168cd [swift] Make swift module public (#7274) 2022-04-26 18:58:51 +02:00
Bogdan Opanchuk
76d3cca19c Rust: fix a name conflict when building with "no_std" feature (#7268)
* Fix a name conflict when building with "no_std" feature

* Bump patch version
2022-04-25 13:09:41 -04:00
Derek Bailey
c86e6d0e30 json inf parsing 2022-04-22 12:24:26 -07:00
Derek Bailey
d34dc32c20 fix include order 2022-04-22 11:19:04 -07:00
Derek Bailey
234d86c92a fixed off-by-one in parser 2022-04-21 21:22:20 -07:00
Derek Bailey
746c73b910 Add Annotations for Monster schema and example buffer 2022-04-21 20:43:55 -07:00
Derek Bailey
0bbfd4b2e3 fixes for annotator 2022-04-21 11:46:16 -07:00
Joakim Hassila
7165219535 Update readme.md (#7257)
Added Swift to supported languages.
2022-04-20 09:49:35 -07:00
Joakim Hassila
a45f564cf1 [performance] Add aggressive systematic inlining in ByteBuffer and FlatBufferBuilder (#7253)
Co-authored-by: Joakim Hassila <hassila@users.noreply.github.com>
2022-04-20 08:59:47 +02:00
Derek Bailey
9d45a64036 more google merge fixes 2022-04-19 14:35:20 -07:00
Derek Bailey
ccfb4c20bf Handle +/-inf in protos (#7256)
* Handle +/-inf in protos

* Check for digit in 4th pos
2022-04-19 13:07:26 -07:00
Derek Bailey
7bcd857b87 Specialize CreateVector with std::initializer_list (#7254) 2022-04-19 13:06:50 -07:00
Joakim Hassila
23c8ab34c1 Swift update performance benchmark infrastructure (#7255)
* Keep the underlying storage capacity when clearing the FlatBufferBuilder. Gives a significant performance boost for serialisation of many small messages.

* Use Googles Swift benchmark library for more consistent results and dynamic number of iterations, simplification of tests as result.

Co-authored-by: Joakim Hassila <hassila@users.noreply.github.com>
2022-04-19 10:52:10 +02:00
Derek Bailey
70002dc5ca various fixes for google merge 2022-04-18 21:15:35 -07:00
Derek Bailey
6e0e79f24f Add test for nested buffer verifier (#7252)
* Add test for nested buffer verifier

* switch to base API
2022-04-18 10:20:06 -07:00
mustiikhalil
b856368d75 Turn off go modules temporary until we get a proper fix (#7251) 2022-04-16 15:29:18 -07:00
Joakim Hassila
e37156a305 Keep the underlying storage capacity when clearing the FlatBufferBuilder. Gives a significant performance boost for serialisation of many small messages. (#7250) 2022-04-16 11:25:44 +02:00
Derek Bailey
a10b0e5464 Java namer variable keep case (#7249) 2022-04-15 16:33:35 -07:00
Derek Bailey
275b739944 allow overriding FLATBUFFERS_MAX_ALIGNMENT 2022-04-15 11:56:34 -07:00
Derek Bailey
9d1ce9a100 Add parameter back to EndVector (#7246) 2022-04-15 11:24:05 -07:00
Casper
79afe6c3d2 Make Java namespaces keep case by default (#7243)
Co-authored-by: Casper Neo <cneo@google.com>
2022-04-13 16:01:48 -07:00
Derek Bailey
c6dbb22300 Add write permissions for labeller 2022-04-13 14:15:38 -07:00
Henner Zeller
18bacd3ea5 Expand test to make sure {}-initializers are properly understood by template. (#7242)
Since CreateVectorOfStrings() takes a templated container, make sure that
the default template deduction from just an initializer list will
still work.

Signed-off-by: Henner Zeller <hzeller@google.com>
2022-04-13 14:13:32 -07:00
Derek Bailey
a2c913aec3 Add -Wnon-virtual-dtor 2022-04-12 16:22:39 -07:00
Derek Bailey
67b33b2942 set workflows permissions to read-only (#7239) 2022-04-11 20:01:00 -07:00
Paulo Pinheiro
7b5fd2bd05 [Kotlin] Fix key lookup returning null clashing with default value (#7237)
* [Java] Fix key lookup returning null clashing with default value

A field with key attribute must always be written on the message so it
can be looked up by key. There is a edge case where inserting a key
field with same value as default would prevent it to be written on
the message and later cannot be found when searched by key.

* [Kotlin] Fix key lookup returning null clashing with default value

A field with key attribute must always be written on the message so it
can be looked up by key. There is a edge case where inserting a key
field with same value as default would prevent it to be written on
the message and later cannot be found when searched by key.

Co-authored-by: Derek Bailey <derekbailey@google.com>
2022-04-11 17:17:19 -07:00
Paulo Pinheiro
7181d77700 [Java] Fix key lookup returning null clashing with default value (#7236)
A field with key attribute must always be written on the message so it
can be looked up by key. There is a edge case where inserting a key
field with same value as default would prevent it to be written on
the message and later cannot be found when searched by key.
2022-04-11 17:16:41 -07:00
Henner Zeller
7f663b1204 Allow CreateVectorOfStrings() to work with any string-type. (#7238)
Any string type that is supported by CreateString(), e.g.
const char* or string_view will now also work.

Signed-off-by: Henner Zeller <hzeller@google.com>
2022-04-11 17:02:19 -07:00
mustiikhalil
173ebb6944 Fixes a bug where the create function doesnt optional + required items (#7228)
Format sh file
2022-04-08 15:28:54 -07:00
Paulo Pinheiro
d658239484 [Kotlin] Update gradle to 7.4.1 and simplify config files. (#7231)
* [Kotlin] Update gradle to 7.4.1 and simplify config files.

* [Kotlin] Add wrapper-validation-action to Kotlin Linux

* [Kotlin] Remove benchmark actions to reduce CI time

* [Kotlin] Move CI js test to Linux action, to increase Mac action speed

* [Kotlin] Generate gradle wrapper in order to be validate

Gradle wrapper from 3.3 to 4.0 are not verifiable because those files
were dynamically generated by Gradle in a non-reproducible way.

So they are now regenerated and will be checked using gitlab action:
gradle/wrapper-validation-action@v1
2022-04-08 11:23:13 -07:00
Derek Bailey
ab4bf59e8c remove toascii (#7234) 2022-04-07 20:48:26 -07:00
Derek Bailey
eee44bbb26 disable cpp-linter (#7229) 2022-04-06 15:03:43 -07:00
Derek Bailey
a63fa51a15 Create cpp-linter.yml (#7208)
* Create cpp-linter.yml

* Update cpp-linter.yml

* Update cpp-linter.yml

* Update bfbs_gen_lua.cpp

make some ill-formed edits to see if the linter flags them.

* Update cpp-linter.yml

Configured tidy checks

* Update cpp-linter.yml

Build project before linting to get compile_commands.json

* Update cpp-linter.yml

* Update cpp-linter.yml

* Update cpp-linter.yml

* Update cpp-linter.yml

* Update cpp-linter.yml

* lines only
2022-04-06 14:18:36 -07:00
mustiikhalil
2049e52101 Adds a way to verify/exposes Entities ids (#7221) 2022-04-06 22:54:01 +02:00
mustiikhalil
832c618f5f Adds implementation flag for swift (#7202)
* Adds implementation flag for swift

Forces internal flag when using @_implementationOnly in swift

Fixes access type for verifier functions & encoder functions

Updates generated code

* Addresses PR comments & adds a code gen dir within the swift tests

* Adds test case for no-include

* Fixes code gen script

Removes prefix
2022-04-06 13:31:38 -07:00
Derek Bailey
14615699fa Started to migrate to target_compile_options (#7222)
* Started to migrate to target_compile_options

* combined compile options together. Added Mac CI builds

* remove arm build (not supported). Fixed old-style-casts

* moved to using a ProjectConfig interface library to specify options

* remove the explicit CMAKE_CXX_STANDARD
2022-04-06 13:25:43 -07:00
avaliente-bc
20aad0c41e [C++] stl_emulation span::count_ is not const anymore (#7226) (#7227)
In C++ we cannot have both assignment operator and const member. Since
span::operator= is defined, span::count_ constness must be removed.
2022-04-06 12:27:37 -07:00
Derek Bailey
f083b33f2a code gen flexbuffer verifier (#7207)
* code gen flexbuffer verifier

* remove verify nested flexbuffers from flexbuffers

* made function static, and placed higher in file

* moved function to own header
2022-04-05 16:29:42 -07:00
Stefan F
bf17df346e [C++] generate sorted #include directives (#7213)
* [C++] generate sorted #include directives

* using stable_sort instead of sort.
2022-04-04 15:20:55 -07:00
Stefan F
35281dedb5 Fix for [C++] flatc generates invalid Code in the default constructor for structs, when --cpp-field-case-style is used #7209 (#7211)
* Typo in flatc options (warning-as-errors instead of warnings-as-errors)

* VerifySizePrefixed (reflection::Schema) and GetAnySizePrefixedRoot added

* some review comments

* more review comments

* Fix for https://github.com/google/flatbuffers/issues/7209

* Fixes [C++] flatc generates invalid Code for union field accessors, when --cpp-field-case-style is used #7210
2022-04-01 13:35:57 -07:00
Jamie-Jameson
c9651b7420 Add overloads for C# ByteBuffer/FlatBufferBuilder to allow adding vector blocks from ArraySegments or IntPtr (#7193)
* Add overloads to Add/Put for ArraySegment and IntPtr

In order to allow using code to reduce memory allocations, add overloads to ByteBuffer's and FlatBuffersBuilder's Put/Add methods that take ArraySegment<T> or IntPtr respectively.
Also, adaptions to the c# code generator in flatc to emit corresponding CreateVectorBlock() overloads

* Add missing files generated with generate_code.py

The previous commit changed the C# code generate, but didn't contain the updated generated test files.

* Incorporate review findings

(1) Adhere to 80 characters limit.
(2) In FlatBufferBuilder.Add(IntPtr,int), move zero length check topmost and add sanity check against negative input
2022-04-01 13:35:07 -07:00
Derek Bailey
26c3b3adab Update codeql.yml
Replaced autobuild with cmake and make.
2022-03-31 22:19:51 -07:00
Derek Bailey
da6e1b9856 Update codeql.yml
Disable all languages other than c++
2022-03-31 21:44:17 -07:00
Derek Bailey
ad27d751e3 Added Oss fuzz badge 2022-03-31 21:14:09 -07:00
Derek Bailey
0aab623cb1 Create codeql.yml 2022-03-31 21:08:30 -07:00
Derek Bailey
6a446bdd83 maximize parallel builds in CI (#7206) 2022-03-31 21:07:37 -07:00
Derek Bailey
21fb5cbbc9 Create scorecards.yml 2022-03-31 21:00:12 -07:00
Derek Bailey
0da6f94867 [C++] Static assert on Flatbuffers Version (#7203)
* Static assert on Flatbuffers Version

* add comment
2022-03-31 20:56:41 -07:00
Derek Bailey
59e9713081 reduce fuzzing time to 1 minute in CI 2022-03-31 16:28:53 -07:00
Derek Bailey
40866a8927 fixed padding in struct for annotated binary (#7199) 2022-03-30 16:43:22 -07:00
Casper
b71d968fad Apply Namer prefix/suffix to other generators (#7197)
* Apply Namer prefix/suffix to other generators

* unnecessary .name

Co-authored-by: Casper Neo <cneo@google.com>
2022-03-30 18:45:11 -04:00
Casper
fac0d7be02 Apply Namer to Java. (#7194)
* Started applying Namer to Java.

- Java didn't previously have keyword escaping
- Added prefixes and suffixes to the Namer methods
- TODO: migrate previous namer applications to using pre/suffixes
- Java methods / functions are interesting, it's mostly camel case
  except when it involves a struct/enum name. That section is Keep case
- I changed the casing for some internal arguments/variables. This
  violates the "don't change genfiles" rule that I've been using but it
  shouldn't break user code.
- LegacyJavaMethod2 is interesting. Basically, Java has a "mixed" case
  convention where it's camel case, except for the type/variant name
  itself, which is keep case. So a type foo_bar would become getfoo_bar
  instead of getFooBar.

* small fix

* Namer for Namespaces

* removed unused parameter, add const everywhere

* Remove unused argument

* More unused args

* Use mutable reference out parameters

* Made more strings const and inlined const empty strings

* remove do not submit

Co-authored-by: Casper Neo <cneo@google.com>
2022-03-30 18:13:16 -04:00
tira-misu
6c5603fd98 [C#] Fix collision of field name and type name (#7149)
* 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 example for type field name collision
2022-03-30 12:51:58 -07:00
Derek Bailey
2d21853a7e monster fuzzer fix for json default scalars 2022-03-30 12:29:41 -07:00
Keith Smiley
fec1a8d015 [swift] Add bazel configuration for Swift (#7195)
* [swift] Add bazel configuration for Swift

This change adds a simple bazel BUILD file for consuming the Swift
support. This also bumps the platforms bazel repo to fix support for M1s
and bazel 5.1+ https://github.com/bazelbuild/bazel/issues/15099#issuecomment-1075368289

The rules_swift inclusion here must happen before gRPC to ensure we
don't pull in an older version.

* Add CC=clang which is a requirement for Swift on Linux

* Add Swift to PATH
2022-03-29 21:30:33 -07:00
Derek Bailey
7fd8576233 structured comments (#7192) 2022-03-29 10:01:32 -07:00
Casper
a4cb1599d8 Namerdart (#7187)
* Apply Namer to Dart.

- Also refactor idl_gen_dart a bit
  - to use more const and references
  - out parameters should be the last argument

* Add keyword test

* minor fixes

* fix merge

* extra 's'

* move dart keyord into dart dir

* Address comments

* Use $ for escaping keywords
* Outparameters for namespace_map

* Escape dollar in toString

* Escape dollar in toString2

* Use UpperCamelCase for types and variants

* try to fix ToString

* namer Type fixes

* Remove path prefixing in imports

* gen code

Co-authored-by: Casper Neo <cneo@google.com>
2022-03-28 18:07:09 -04:00
Derek Bailey
ae4ce72651 fuzzed binary annotator (#7188) 2022-03-25 22:58:15 -07:00
Derek Bailey
e2be0c0b06 Handle root offset and root table vtable invalidation (#7177)
* Handle invalid root offset

* Handle vtable offset invalidation

* Added script generator. Add more cases through vtable ref table size

* review responses

* vtable offset validation

* Moved padding insertion to the end. Tests invalid field lenghts

* table offsets validated. Added type after field

* validate string length

* add todo

* invalid vector length

* invalid structs

* general cleanup

* reworded invalid offsets

* example for vector of structs

* invalid vector of tables

* invalid vector of strings

* invalid vector of scalars

* vector of unions

* validate union type value

* invalid vector union type values
2022-03-23 21:51:32 -07:00
tira-misu
2ad408697f [TS] Fix generation of struct members in object api (#7148)
* 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

* [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
2022-03-23 21:40:11 -07:00
Stefan F
4213d91054 VerifySizePrefixed (reflection::Schema) and GetAnySizePrefixedRoot added (#7181)
* Typo in flatc options (warning-as-errors instead of warnings-as-errors)

* VerifySizePrefixed (reflection::Schema) and GetAnySizePrefixedRoot added

* some review comments

* more review comments
2022-03-23 21:39:38 -07:00
Will Hughes
5a13f622cf Correctly parse lists of enums in Dart generated code (#7157)
* Correctly parse lists of enums in Dart generated code

* Add a test for #6869

* Commit generated code

* Fixed missing newline-at-eof
2022-03-22 21:56:14 -07:00
mustiikhalil
23a7e4e0b0 Adds no-includes flags to the swift code generator (#7182) 2022-03-22 21:42:20 -07:00
James Kuszmaul
eeb49c2757 Move flatbuffer_ts_library to typescript.bzl (#7183)
This makes it so that users of flatbuffer_cc_library don't need to have
rules_nodejs available in their WORKSPACE, addressing #7179.
2022-03-22 21:41:39 -07:00
Stefan F
824763b316 Typo in flatc options (warning-as-errors instead of warnings-as-errors) (#7180) 2022-03-21 18:08:14 -04:00
Derek Bailey
d3aeee32bb Annotated Flatbuffer Binary (#7174)
* Annotated Flatbuffer Binary

* Various fixes

* Handles old schema

* handle multiple missing fields

* minor edits

* bazel fix, spelling fix, ascii fix
2022-03-18 14:08:05 -07:00
Derek Bailey
0bceba24db [Lua] Apply Namer to Lua (#7171)
* Apply Namer to Lua bfbs code gen

* refactor namer into IdlNamer to keep idl includes separate

* remove commented out code

* added bfbs_namer

* remove Enum case

* add to bazel
2022-03-15 21:48:42 -07:00
David Schneider
b8c77d4041 Make inclusion of header <optional> opt-out via macro (#7168)
* Allow suppression of including <optional> via macro

* Combine preprocessor conditions

* Make inclusion of header <optional> opt-in

* Make inclusion of <optional> opt-out via macro

* Auto-detect C++17+ when defining macro

* Enclose macro expression in parentheses

* Check value of macro, not whether it's defined

* Fix parentheses

* Don't define macro with expression using other macros

The preprocessor doesn't seem to like it.

* Fix parentheses
2022-03-15 17:52:11 -07:00
Casper
8468eab83b Namersw (#7167)
* Define and use Namer overloads

* more

* NamespacedType needs a public string-like overload

* Move Rust FieldOffsetName to Namer LegacyRustFieldOffsetName

* Started swift

* More Namer updates

* Remove more usage of the variable 'name' which was semantically overloaded

* unshadow varible

* Make ptr to bool explicit

Co-authored-by: Casper Neo <cneo@google.com>
2022-03-13 18:46:27 -04:00
Casper
2b2e8d4aec Nameroverloads (#7164)
* Define and use Namer overloads

* more

* NamespacedType needs a public string-like overload

* Move Rust FieldOffsetName to Namer LegacyRustFieldOffsetName

Co-authored-by: Casper Neo <cneo@google.com>
2022-03-13 16:54:45 -04:00
Markus
b80b32bfaf Use DESCRIPTION only if CMake version >= 3.9 (#7166) 2022-03-13 12:49:18 -07:00
James Kuszmaul
e5f331db99 [TS] Add single-file ts codegen & bazel rule for typescript (#7161)
The headline here is adding a flatbuffer_ts_library rule for generating
typescript code in bazel. This entails some non-trivial other changes,
but ideally none are user-visible.

In particular:
* Added a --ts-flat-file flag that generates a single *_generated.ts
  file instead of separate files for each typescript type. This makes
  bazel much happier.
* Import the bazel rules_nodejs stuff needed to support building
  typescript in bazel
* Move flatbuffers.ts to index.ts because I wasn't sure how to make
  bazel comprehend the "main" attribute of the package.json. Happy
  to take another stab at figuring that out if really needed.
* Fix another couple keyword escaping spots in typescript...
2022-03-10 10:08:13 -08:00
Casper
2f84c60385 Apply Namer to Go code gen (#7150)
* Refactor out a  class from Rust Codegen

* Convert GenerateRustModuleRootFile

* git-clang-format

* unused variable

* parenthesis

* update BUILD file

* buildifier

* Delete bfbs_gen_rust.h

* Delete bfbs_gen_rust.cpp

* Addressed some comments

* Namer::EnumVariant

* Remove do not submit; Add Namespace vector overload

* Unshadow variable

* removed redundant variables

* Apply Namer to Python

* Use more variables a bit

* Apply const a bunch

* More variables

* Fix ObjectTypes

* git clang format

* small thing

* Simplified code around nested flatbuffers

* Make more methods const.

* Python files are kKeep case

* Address DO NOT SUBMIT in SaveType

* ensure dir exists before saving files

* clang format

Co-authored-by: Casper Neo <cneo@google.com>
2022-03-08 20:53:05 -05:00
Wouter van Oortmerssen
d648396515 [Lobster] file_identifier support 2022-03-08 15:39:12 -08:00
Wouter van Oortmerssen
777e78d8dd [Lobster] support unsigned integer reads
(depends on the latest Lobster version)
2022-03-08 15:13:34 -08:00
Casper
4016c549d3 Apply Namer to Python code gen (#7146)
* Refactor out a  class from Rust Codegen

* Convert GenerateRustModuleRootFile

* git-clang-format

* unused variable

* parenthesis

* update BUILD file

* buildifier

* Delete bfbs_gen_rust.h

* Delete bfbs_gen_rust.cpp

* Addressed some comments

* Namer::EnumVariant

* Remove do not submit; Add Namespace vector overload

* Unshadow variable

* removed redundant variables

* Apply Namer to Python

* Use more variables a bit

* Apply const a bunch

* More variables

* Fix ObjectTypes

* git clang format

* small thing

* Simplified code around nested flatbuffers

* Make more methods const.

* Python files are kKeep case

* Address DO NOT SUBMIT in SaveType

* ensure dir exists before saving files

* fix space

Co-authored-by: Casper Neo <cneo@google.com>
2022-03-07 19:24:46 -05:00
Casper
40827b21b2 Fix missing 'break' (#7151)
Co-authored-by: Casper Neo <cneo@google.com>
2022-03-07 11:53:20 -05:00
Casper
65a10b6e32 Implement a config based name manager and use it in Rust codegen (#7144)
* Refactor out a  class from Rust Codegen

* Convert GenerateRustModuleRootFile

* git-clang-format

* unused variable

* parenthesis

* update BUILD file

* buildifier

* Delete bfbs_gen_rust.h

* Delete bfbs_gen_rust.cpp

* Addressed some comments

* Namer::EnumVariant

* Remove do not submit; Add Namespace vector overload

* Unshadow variable

* removed redundant variables

* Warn if converting from kKeep case.

Co-authored-by: Casper Neo <cneo@google.com>
2022-03-05 20:43:57 -05:00
James Kuszmaul
8db2fef3f7 [TS] Escape keywords in typescript object names (#7137)
* Add Object to the list of reserved keywords.
* Properly escape keywords in type names.
* Properly escape keywords in enum names.
* Properly escape keywords in enum field names.
2022-03-05 09:39:59 -08:00
James Kuszmaul
9ed1323044 Fix 64-bit numeric enum values in typescript (#7135)
* Fix 64-bit default numeric enum values in typescript

If you had a default value that wasn't a valid enum value (e.g., a zero
if you used a bit_flag setting, like you get with AdvancedFeatures
in reflection.fbs), we weren't using BigInt.

* Run generate_code.py

* [DART] Handle deprecated fields & invalid enum defaults

* Update .NET test
2022-03-04 21:57:48 -08:00
Derek Bailey
1a4c405662 updated npm to 2.0.6 2022-02-24 22:21:36 -08:00
Derek Bailey
318594e4b4 prevent name clash (#7133) 2022-02-24 22:01:25 -08:00
Casper
3d903302c3 [Rust] Add length checks to arrays and vectors. (#7130)
* [Rust] Add length checks to arrays and vectors.

The previous behavior allowed for out of bounds access in
the public API (#7011).

* bump semver and test warning

Co-authored-by: Casper Neo <cneo@google.com>
2022-02-24 13:49:59 -05:00
Derek Bailey
c9571d9897 Replaced ToDasherCase with ConvertCase (#7131) 2022-02-23 22:31:40 -06:00
Derek Bailey
3694b830a2 Use ConvertCase instead of Make{Upper,Lower,Snake} implementations (#7127)
* Unified name case conversion to single method

* Convert bfbs_gen to use ConvertCase

* convert rust to use ConvertCase

* Convert idl_parser to use ConvertCase

* Convert MakeScreamingCamel to ConvertCase

* Replaced MakeCamel with ConvertCase

* minor fixes
2022-02-23 18:08:11 -06:00
Derek Bailey
0471fa807c remove stall reference to version 2022-02-22 16:41:42 -08:00
Derek Bailey
914344ea9b some minor help edits 2022-02-22 15:52:51 -08:00
Derek Bailey
b40266c56f Use target_compile_features to target C++11 (#7122) 2022-02-22 17:12:11 -06:00
Derek Bailey
8a9303d464 update proto tests with alaised enum (#7121) 2022-02-22 01:03:46 -06:00
Derek Bailey
30c4bf47f9 Trigger fuzzing CI only on relevant changes (#7120) 2022-02-21 23:44:04 -06:00
Derek Bailey
46ce45601b remove auto generate code from cmakelists (#7119) 2022-02-21 23:33:42 -06:00
anov21
433312c55a add the missing checkNullConditionnal code in the "GenObjApi" function when the field is scalar optional (#7114) 2022-02-21 22:34:37 -06:00
James Kuszmaul
9c52ec3744 Add deps attribute to flatbuffer_cc_library (#7107)
I'm not seeing the reason why we didn't attempt to support transitive
dependencies for flatbuffer_cc_library, and the current setup makes
having to propagate new dependencies to all of their recursive
dependents obnoxious.
2022-02-21 22:33:47 -06:00
Derek Bailey
70e2f49bff fixed string-json -> strict-json typo 2022-02-21 20:26:40 -08:00
tira-misu
5ac0367ed3 [TS] Fix generation of reserved words in object api (#7106) (#7115)
* 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)
2022-02-21 22:13:40 -06:00
Meer Suri
5d101afb52 Fix minor typo in WhitePaper.md (#7108) 2022-02-18 21:29:21 -08:00
Christopher Crawford
06f4af11b6 Go optional scalars (#7104)
* [go] always write required types

* support optional scalars in go

* generate optional_scalars and monster_test

* restore original behavior for non-optional scalars

* add tests
2022-02-16 15:02:54 -05:00
Derek Bailey
57e338f819 explicitly use windows-2019 to unblock ci (#7105) 2022-02-15 18:10:53 -08:00
1764 changed files with 182571 additions and 59731 deletions

View File

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

5
.bazelignore Normal file
View File

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

18
.bazelrc Normal file
View File

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

View File

@@ -1,13 +1,5 @@
---
Language: Cpp
BasedOnStyle: Google
DerivePointerAlignment: false
PointerAlignment: Right
IndentPPDirectives: AfterHash
Cpp11BracedListStyle: false
AlwaysBreakTemplateDeclarations: false
AllowShortCaseLabelsOnASingleLine: true
SpaceAfterTemplateKeyword: false
AllowShortBlocksOnASingleLine: true
...

347
.clang-tidy Normal file
View File

@@ -0,0 +1,347 @@
---
FormatStyle: "file"
WarningsAsErrors: "*"
HeaderFilterRegex: ".*"
Checks: "google-build-explicit-make-pair,
google-build-namespaces,
google-build-using-namespace,
google-default-arguments,
google-explicit-constructor,
google-global-names-in-headers,
google-objc-avoid-nsobject-new,
google-objc-avoid-throwing-exception,
google-objc-function-naming,
google-objc-global-variable-declaration,
google-readability-avoid-underscore-in-googletest-name,
google-readability-braces-around-statements,
google-readability-casting,
google-readability-function-size,
google-readability-namespace-comments,
google-runtime-int,
google-runtime-operator,
google-upgrade-googletest-case,
clang-analyzer-apiModeling.StdCLibraryFunctions,
clang-analyzer-apiModeling.TrustNonnull,
clang-analyzer-apiModeling.google.GTest,
clang-analyzer-apiModeling.llvm.CastValue,
clang-analyzer-apiModeling.llvm.ReturnValue,
clang-analyzer-core.CallAndMessage,
clang-analyzer-core.CallAndMessageModeling,
clang-analyzer-core.DivideZero,
clang-analyzer-core.DynamicTypePropagation,
clang-analyzer-core.NonNullParamChecker,
clang-analyzer-core.NonnilStringConstants,
clang-analyzer-core.NullDereference,
clang-analyzer-core.StackAddrEscapeBase,
clang-analyzer-core.StackAddressEscape,
clang-analyzer-core.UndefinedBinaryOperatorResult,
clang-analyzer-core.VLASize,
clang-analyzer-core.builtin.BuiltinFunctions,
clang-analyzer-core.builtin.NoReturnFunctions,
clang-analyzer-core.uninitialized.ArraySubscript,
clang-analyzer-core.uninitialized.Assign,
clang-analyzer-core.uninitialized.Branch,
clang-analyzer-core.uninitialized.CapturedBlockVariable,
clang-analyzer-core.uninitialized.UndefReturn,
clang-analyzer-cplusplus.InnerPointer,
clang-analyzer-cplusplus.Move,
clang-analyzer-cplusplus.NewDelete,
clang-analyzer-cplusplus.NewDeleteLeaks,
clang-analyzer-cplusplus.PlacementNew,
clang-analyzer-cplusplus.PureVirtualCall,
clang-analyzer-cplusplus.SelfAssignment,
clang-analyzer-cplusplus.SmartPtrModeling,
clang-analyzer-cplusplus.StringChecker,
clang-analyzer-cplusplus.VirtualCallModeling,
clang-analyzer-deadcode.DeadStores,
clang-analyzer-fuchsia.HandleChecker,
clang-analyzer-nullability.NullPassedToNonnull,
clang-analyzer-nullability.NullReturnedFromNonnull,
clang-analyzer-nullability.NullabilityBase,
clang-analyzer-nullability.NullableDereferenced,
clang-analyzer-nullability.NullablePassedToNonnull,
clang-analyzer-nullability.NullableReturnedFromNonnull,
clang-analyzer-optin.cplusplus.UninitializedObject,
clang-analyzer-optin.cplusplus.VirtualCall,
clang-analyzer-optin.mpi.MPI-Checker,
clang-analyzer-optin.osx.OSObjectCStyleCast,
clang-analyzer-optin.osx.cocoa.localizability.EmptyLocalizationContextChecker,
clang-analyzer-optin.osx.cocoa.localizability.NonLocalizedStringChecker,
clang-analyzer-optin.performance.GCDAntipattern,
clang-analyzer-optin.performance.Padding,
clang-analyzer-optin.portability.UnixAPI,
clang-analyzer-osx.API,
clang-analyzer-osx.MIG,
clang-analyzer-osx.NSOrCFErrorDerefChecker,
clang-analyzer-osx.NumberObjectConversion,
clang-analyzer-osx.OSObjectRetainCount,
clang-analyzer-osx.ObjCProperty,
clang-analyzer-osx.SecKeychainAPI,
clang-analyzer-osx.cocoa.AtSync,
clang-analyzer-osx.cocoa.AutoreleaseWrite,
clang-analyzer-osx.cocoa.ClassRelease,
clang-analyzer-osx.cocoa.Dealloc,
clang-analyzer-osx.cocoa.IncompatibleMethodTypes,
clang-analyzer-osx.cocoa.Loops,
clang-analyzer-osx.cocoa.MissingSuperCall,
clang-analyzer-osx.cocoa.NSAutoreleasePool,
clang-analyzer-osx.cocoa.NSError,
clang-analyzer-osx.cocoa.NilArg,
clang-analyzer-osx.cocoa.NonNilReturnValue,
clang-analyzer-osx.cocoa.ObjCGenerics,
clang-analyzer-osx.cocoa.RetainCount,
clang-analyzer-osx.cocoa.RetainCountBase,
clang-analyzer-osx.cocoa.RunLoopAutoreleaseLeak,
clang-analyzer-osx.cocoa.SelfInit,
clang-analyzer-osx.cocoa.SuperDealloc,
clang-analyzer-osx.cocoa.UnusedIvars,
clang-analyzer-osx.cocoa.VariadicMethodTypes,
clang-analyzer-osx.coreFoundation.CFError,
clang-analyzer-osx.coreFoundation.CFNumber,
clang-analyzer-osx.coreFoundation.CFRetainRelease,
clang-analyzer-osx.coreFoundation.containers.OutOfBounds,
clang-analyzer-osx.coreFoundation.containers.PointerSizedValues,
clang-analyzer-security.FloatLoopCounter,
clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling,
clang-analyzer-security.insecureAPI.SecuritySyntaxChecker,
clang-analyzer-security.insecureAPI.UncheckedReturn,
clang-analyzer-security.insecureAPI.bcmp,
clang-analyzer-security.insecureAPI.bcopy,
clang-analyzer-security.insecureAPI.bzero,
clang-analyzer-security.insecureAPI.decodeValueOfObjCType,
clang-analyzer-security.insecureAPI.getpw,
clang-analyzer-security.insecureAPI.gets,
clang-analyzer-security.insecureAPI.mkstemp,
clang-analyzer-security.insecureAPI.mktemp,
clang-analyzer-security.insecureAPI.rand,
clang-analyzer-security.insecureAPI.strcpy,
clang-analyzer-security.insecureAPI.vfork,
clang-analyzer-unix.API,
clang-analyzer-unix.DynamicMemoryModeling,
clang-analyzer-unix.Malloc,
clang-analyzer-unix.MallocSizeof,
clang-analyzer-unix.MismatchedDeallocator,
clang-analyzer-unix.Vfork,
clang-analyzer-unix.cstring.BadSizeArg,
clang-analyzer-unix.cstring.CStringModeling,
clang-analyzer-unix.cstring.NullArg,
clang-analyzer-valist.CopyToSelf,
clang-analyzer-valist.Uninitialized,
clang-analyzer-valist.Unterminated,
clang-analyzer-valist.ValistBase,
clang-analyzer-webkit.NoUncountedMemberChecker,
clang-analyzer-webkit.RefCntblBaseVirtualDtor,
clang-analyzer-webkit.UncountedLambdaCapturesChecker,
################################################ Optional checks ################################################
#google-readability-todo,
#bugprone-argument-comment,
#bugprone-assert-side-effect,
#bugprone-bad-signal-to-kill-thread,
#bugprone-bool-pointer-implicit-conversion,
#bugprone-branch-clone,
#bugprone-copy-constructor-init,
#bugprone-dangling-handle,
#bugprone-dynamic-static-initializers,
#bugprone-easily-swappable-parameters,
#bugprone-exception-escape,
#bugprone-fold-init-type,
#bugprone-forward-declaration-namespace,
#bugprone-forwarding-reference-overload,
#bugprone-implicit-widening-of-multiplication-result,
#bugprone-inaccurate-erase,
#bugprone-incorrect-roundings,
#bugprone-infinite-loop,
#bugprone-integer-division,
#bugprone-lambda-function-name,
#bugprone-macro-parentheses,
#bugprone-macro-repeated-side-effects,
#bugprone-misplaced-operator-in-strlen-in-alloc,
#bugprone-misplaced-pointer-arithmetic-in-alloc,
#bugprone-misplaced-widening-cast,
#bugprone-move-forwarding-reference,
#bugprone-multiple-statement-macro,
#bugprone-narrowing-conversions,
#bugprone-no-escape,
#bugprone-not-null-terminated-result,
#bugprone-parent-virtual-call,
#bugprone-posix-return,
#bugprone-redundant-branch-condition,
#bugprone-reserved-identifier,
#bugprone-signal-handler,
#bugprone-signed-char-misuse,
#bugprone-sizeof-container,
#bugprone-sizeof-expression,
#bugprone-spuriously-wake-up-functions,
#bugprone-string-constructor,
#bugprone-string-integer-assignment,
#bugprone-string-literal-with-embedded-nul,
#bugprone-stringview-nullptr,
#bugprone-suspicious-enum-usage,
#bugprone-suspicious-include,
#bugprone-suspicious-memory-comparison,
#bugprone-suspicious-memset-usage,
#bugprone-suspicious-missing-comma,
#bugprone-suspicious-semicolon,
#bugprone-suspicious-string-compare,
#bugprone-swapped-arguments,
#bugprone-terminating-continue,
#bugprone-throw-keyword-missing,
#bugprone-too-small-loop-variable,
#bugprone-undefined-memory-manipulation,
#bugprone-undelegated-constructor,
#bugprone-unhandled-exception-at-new,
#bugprone-unhandled-self-assignment,
#bugprone-unused-raii,
#bugprone-unused-return-value,
#bugprone-use-after-move,
#bugprone-virtual-near-miss,
#cppcoreguidelines-avoid-c-arrays,
#cppcoreguidelines-avoid-goto,
#cppcoreguidelines-avoid-magic-numbers,
#cppcoreguidelines-avoid-non-const-global-variables,
#cppcoreguidelines-c-copy-assignment-signature,
#cppcoreguidelines-explicit-virtual-functions,
#cppcoreguidelines-init-variables,
#cppcoreguidelines-interfaces-global-init,
#cppcoreguidelines-macro-usage,
#cppcoreguidelines-narrowing-conversions,
#cppcoreguidelines-no-malloc,
#cppcoreguidelines-non-private-member-variables-in-classes,
#cppcoreguidelines-owning-memory,
#cppcoreguidelines-prefer-member-initializer,
#cppcoreguidelines-pro-bounds-array-to-pointer-decay,
#cppcoreguidelines-pro-bounds-constant-array-index,
#cppcoreguidelines-pro-bounds-pointer-arithmetic,
#cppcoreguidelines-pro-type-const-cast,
#cppcoreguidelines-pro-type-cstyle-cast,
#cppcoreguidelines-pro-type-member-init,
#cppcoreguidelines-pro-type-reinterpret-cast,
#cppcoreguidelines-pro-type-static-cast-downcast,
#cppcoreguidelines-pro-type-union-access,
#cppcoreguidelines-pro-type-vararg,
#cppcoreguidelines-slicing,
#cppcoreguidelines-special-member-functions,
#cppcoreguidelines-virtual-class-destructor,
#hicpp-avoid-c-arrays,
#hicpp-avoid-goto,
#hicpp-braces-around-statements,
#hicpp-deprecated-headers,
#hicpp-exception-baseclass,
#hicpp-explicit-conversions,
#hicpp-function-size,
#hicpp-invalid-access-moved,
#hicpp-member-init,
#hicpp-move-const-arg,
#hicpp-multiway-paths-covered,
#hicpp-named-parameter,
#hicpp-new-delete-operators,
#hicpp-no-array-decay,
#hicpp-no-assembler,
#hicpp-no-malloc,
#hicpp-noexcept-move,
#hicpp-signed-bitwise,
#hicpp-special-member-functions,
#hicpp-static-assert,
#hicpp-undelegated-constructor,
#hicpp-uppercase-literal-suffix,
#hicpp-use-auto,
#hicpp-use-emplace,
#hicpp-use-equals-default,
#hicpp-use-equals-delete,
#hicpp-use-noexcept,
#hicpp-use-nullptr,
#hicpp-use-override,
#hicpp-vararg,
#modernize-avoid-bind,
#modernize-avoid-c-arrays,
#modernize-concat-nested-namespaces,
#modernize-deprecated-headers,
#modernize-deprecated-ios-base-aliases,
#modernize-loop-convert,
#modernize-make-shared,
#modernize-make-unique,
#modernize-pass-by-value,
#modernize-raw-string-literal,
#modernize-redundant-void-arg,
#modernize-replace-auto-ptr,
#modernize-replace-disallow-copy-and-assign-macro,
#modernize-replace-random-shuffle,
#modernize-return-braced-init-list,
#modernize-shrink-to-fit,
#modernize-unary-static-assert,
#modernize-use-auto,
#modernize-use-bool-literals,
#modernize-use-default-member-init,
#modernize-use-emplace,
#modernize-use-equals-default,
#modernize-use-equals-delete,
#modernize-use-nodiscard,
#modernize-use-noexcept,
#modernize-use-nullptr,
#modernize-use-override,
#modernize-use-trailing-return-type,
#modernize-use-transparent-functors,
#modernize-use-uncaught-exceptions,
#modernize-use-using,
#performance-faster-string-find,
#performance-for-range-copy,
#performance-implicit-conversion-in-loop,
#performance-inefficient-algorithm,
#performance-inefficient-string-concatenation,
#performance-inefficient-vector-operation,
#performance-move-const-arg,
#performance-move-constructor-init,
#performance-no-automatic-move,
#performance-no-int-to-ptr,
#performance-noexcept-move-constructor,
#performance-trivially-destructible,
#performance-type-promotion-in-math-fn,
#performance-unnecessary-copy-initialization,
#performance-unnecessary-value-param,
#portability-restrict-system-includes,
#portability-simd-intrinsics,
#readability-avoid-const-params-in-decls,
#readability-braces-around-statements,
#readability-const-return-type,
#readability-container-contains,
#readability-container-data-pointer,
#readability-container-size-empty,
#readability-convert-member-functions-to-static,
#readability-delete-null-pointer,
#readability-duplicate-include,
#readability-else-after-return,
#readability-function-cognitive-complexity,
#readability-function-size,
#readability-identifier-length,
#readability-identifier-naming,
#readability-implicit-bool-conversion,
#readability-inconsistent-declaration-parameter-name,
#readability-isolate-declaration,
#readability-magic-numbers,
#readability-make-member-function-const,
#readability-misleading-indentation,
#readability-misplaced-array-index,
#readability-named-parameter,
#readability-non-const-parameter,
#readability-qualified-auto,
#readability-redundant-access-specifiers,
#readability-redundant-control-flow,
#readability-redundant-declaration,
#readability-redundant-function-ptr-dereference,
#readability-redundant-member-init,
#readability-redundant-preprocessor,
#readability-redundant-smartptr-get,
#readability-redundant-string-cstr,
#readability-redundant-string-init,
#readability-simplify-boolean-expr,
#readability-simplify-subscript-expr,
#readability-static-accessed-through-instance,
#readability-static-definition-in-anonymous-namespace,
#readability-string-compare,
#readability-suspicious-call-argument,
#readability-uniqueptr-delete-release,
#readability-uppercase-literal-suffix,
#readability-use-anyofallof
"

View File

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

View File

@@ -1,13 +0,0 @@
/* eslint-env node */
module.exports = {
root: true,
parser: '@typescript-eslint/parser',
plugins: [
'@typescript-eslint',
],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
]
};

5
.github/CODEOWNERS vendored Normal file
View File

@@ -0,0 +1,5 @@
# Default owner
* @dbaileychess derekbailey@google.com
# Prevent modification of this file
.github/CODEOWNERS @dbaileychess derekbailey@google.com

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

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

View File

@@ -3,7 +3,7 @@ Thank you for submitting a PR!
Please delete this standard text once you've created your own description.
If you make changes to any of the code generators (`src/idl_gen*`) be sure to
build your project, as it will generate code based on the changes. If necessary
[build](https://google.github.io/flatbuffers/flatbuffers_guide_building.html) your project, as it will generate code based on the changes. If necessary
the code generation script can be directly run (`scripts/generate_code.py`),
requires Python3. This allows us to better see the effect of the PR.

152
.github/labeler.yml vendored
View File

@@ -5,91 +5,133 @@
#
# See .github/workflows/label.yml for Github Action workflow script
c#:
- '**/*.cs'
- net/**/*
- tests/FlatBuffers.Test/**/*
- tests/FlatBuffers.Benchmarks/**/*
- src/idl_gen_csharp.cpp
"c#":
- changed-files:
- any-glob-to-any-file:
- '**/*.cs'
- 'net/**/*'
- 'tests/FlatBuffers.Test/**/*'
- 'tests/FlatBuffers.Benchmarks/**/*'
- 'src/idl_gen_csharp.cpp'
swift:
- '**/*.swift'
- swift/**/*
- tests/FlatBuffers.GRPC.Swift/**/*
- tests/FlatBuffers.Benchmarks.swift/**/*
- tests/FlatBuffers.Test.Swift/**/*
- src/idl_gen_swift.cpp
- changed-files:
- any-glob-to-any-file:
- '**/*.swift'
- 'swift/**/*'
- 'tests/swift/**'
- 'src/idl_gen_swift.cpp'
nim:
- changed-files:
- any-glob-to-any-file:
- '**/*.nim'
- 'nim/**/*'
- 'src/idl_gen_nim.cpp'
- 'src/bfbs_gen_nim.cpp'
javascript:
- '**/*.js'
- src/idl_gen_ts.cpp
- changed-files:
- any-glob-to-any-file:
- '**/*.js'
- 'src/idl_gen_ts.cpp'
typescript:
- '**/*.ts'
- src/idl_gen_ts.cpp
- grpc/flatbuffers-js-grpc/**/*.ts
- changed-files:
- any-glob-to-any-file:
- '**/*.ts'
- 'src/idl_gen_ts.cpp'
- 'grpc/flatbuffers-js-grpc/**/*.ts'
golang:
- '**/*.go'
- src/idl_gen_go.cpp
- changed-files:
- any-glob-to-any-file:
- '**/*.go'
- 'src/idl_gen_go.cpp'
python:
- '**/*.py'
- src/idl_gen_python.cpp
- changed-files:
- any-glob-to-any-file:
- '**/*.py'
- 'src/idl_gen_python.cpp'
java:
- '**/*.java'
- src/idl_gen_java.cpp
- changed-files:
- any-glob-to-any-file:
- '**/*.java'
- 'src/idl_gen_java.cpp'
kotlin:
- '**/*.kt'
- src/idl_gen_kotlin.cpp
- changed-files:
- any-glob-to-any-file:
- '**/*.kt'
- 'src/idl_gen_kotlin.cpp'
- 'src/idl_gen_kotlin_kmp.cpp'
lua:
- '**/*.lua'
- lua/**/*
- src/idl_gen_lua.cpp
- src/bfbs_gen_lua.cpp
- changed-files:
- any-glob-to-any-file:
- '**/*.lua'
- 'lua/**/*'
- 'src/bfbs_gen_lua.cpp'
lobster:
- '**/*.lobster'
- src/idl_gen_lobster.cpp
- changed-files:
- any-glob-to-any-file:
- '**/*.lobster'
- 'src/idl_gen_lobster.cpp'
php:
- '**/*.php'
- src/idl_gen_php.cpp
- changed-files:
- any-glob-to-any-file:
- '**/*.php'
- 'src/idl_gen_php.cpp'
rust:
- '**/*.rs'
- rust/**/*
- src/idl_gen_rust.cpp
dart:
- '**/*.dart'
- src/idl_gen_dart.cpp
- changed-files:
- any-glob-to-any-file:
- '**/*.rs'
- 'rust/**/*'
- 'src/idl_gen_rust.cpp'
c++:
- '**/*.cc'
- '**/*.cpp'
- '**/*.h'
dart:
- changed-files:
- any-glob-to-any-file:
- '**/*.dart'
- 'src/idl_gen_dart.cpp'
"c++":
- changed-files:
- any-glob-to-any-file:
- '**/*.cc'
- '**/*.cpp'
- '**/*.h'
json:
- '**/*.json'
- src/idl_gen_json_schema.cpp
- changed-files:
- any-glob-to-any-file:
- '**/*.json'
- 'src/idl_gen_json_schema.cpp'
codegen:
- src/**/*
- changed-files:
- any-glob-to-any-file:
- 'src/**/*'
documentation:
- docs/**/*
- '**/*.md'
- changed-files:
- any-glob-to-any-file:
- 'docs/**/*'
- '**/*.md'
CI:
- '.github/**/*'
- '.travis/**/*'
- '.bazelci/**/*'
- .travis.yml
- changed-files:
- any-glob-to-any-file:
- '.github/**/*'
- '.bazelci/**/*'
grpc:
- grpc/**/*
- src/idl_gen_grpc.cpp
- changed-files:
- any-glob-to-any-file:
- 'grpc/**/*'
- 'src/idl_gen_grpc.cpp'

View File

@@ -1,26 +1,40 @@
name: CI
permissions: read-all
on:
# For manual tests.
workflow_dispatch:
push:
tags:
- "*" # new tag version, like `0.8.4` or else
branches:
- master
pull_request:
branches:
- master
schedule:
# Run daily at 4:45 A.M. to catch dependencies that break us.
- cron: '45 4 * * *'
jobs:
build-linux:
permissions:
contents: write
outputs:
digests-gcc: ${{ steps.hash-gcc.outputs.hashes }}
digests-clang: ${{ steps.hash-clang.outputs.hashes }}
name: Build Linux
runs-on: ubuntu-latest
runs-on: ubuntu-24.04
strategy:
matrix:
cxx: [g++-10, clang++-12]
cxx: [g++-13, clang++-18]
fail-fast: false
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v6
- name: cmake
run: CXX=${{ matrix.cxx }} cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release .
run: CXX=${{ matrix.cxx }} cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON -DFLATBUFFERS_STATIC_FLATC=ON .
- name: build
run: make -j4
run: make -j
- name: test
run: ./flattests
- name: make flatc executable
@@ -28,275 +42,602 @@ jobs:
chmod +x flatc
./flatc --version
- name: upload build artifacts
uses: actions/upload-artifact@v1
uses: actions/upload-artifact@v4
with:
name: Linux flatc binary ${{ matrix.cxx }}
path: flatc
# Below if only for release.
- name: Zip file
if: startsWith(github.ref, 'refs/tags/')
run: zip Linux.flatc.binary.${{ matrix.cxx }}.zip flatc
- name: Release zip file
uses: softprops/action-gh-release@v2
if: startsWith(github.ref, 'refs/tags/')
with:
files: Linux.flatc.binary.${{ matrix.cxx }}.zip
- name: Generate SLSA subjects - clang
if: matrix.cxx == 'clang++-18' && startsWith(github.ref, 'refs/tags/')
id: hash-clang
run: echo "hashes=$(sha256sum Linux.flatc.binary.${{ matrix.cxx }}.zip | base64 -w0)" >> $GITHUB_OUTPUT
- name: Generate SLSA subjects - gcc
if: matrix.cxx == 'g++-13' && startsWith(github.ref, 'refs/tags/')
id: hash-gcc
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
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v6
- name: cmake
run: CXX=clang++-18 cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON -DFLATBUFFERS_CXX_FLAGS="-DFLATBUFFERS_NO_FILE_TESTS" .
- name: build
run: make -j
- name: test
run: ./flattests
build-linux-out-of-source:
name: Build Linux with out-of-source build location
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v6
- name: make build directory
run: mkdir build
- name: cmake
working-directory: build
run: >
CXX=clang++-18 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-24.04
strategy:
fail-fast: false
matrix:
std: [11, 14, 17, 20, 23]
cxx: [g++-13, clang++-18]
exclude:
# Clang++15 10.3.0 stdlibc++ doesn't fully support std 23
- cxx: clang++-18
std: 23
steps:
- uses: actions/checkout@v6
- name: cmake
run: >
CXX=${{ matrix.cxx }} cmake -G "Unix Makefiles"
-DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON
-DFLATBUFFERS_CPP_STD=${{ matrix.std }}
-DFLATBUFFERS_BUILD_CPP17=${{ matrix.std >= 17 && 'On' || 'Off'}}
- name: build
run: make -j
- name: test
run: ./flattests
- name: test C++17
if: matrix.std >= 17
run: ./flattests_cpp17
build-cpp-std:
name: Build Windows C++
runs-on: windows-2022
strategy:
matrix:
std: [11, 14, 17, 20, 23]
fail-fast: false
steps:
- uses: actions/checkout@v6
- name: Add msbuild to PATH
uses: microsoft/setup-msbuild@v2
- name: cmake
run: >
cmake -G "Visual Studio 17 2022" -A x64 -DCMAKE_BUILD_TYPE=Release
-DFLATBUFFERS_STRICT_MODE=ON
-DFLATBUFFERS_CPP_STD=${{ matrix.std }}
-DFLATBUFFERS_BUILD_CPP17=${{ matrix.std >= 17 && 'On' || 'Off'}}
- name: build
run: msbuild.exe FlatBuffers.sln /p:Configuration=Release /p:Platform=x64
- name: test
run: Release\flattests.exe
- name: test C++17
if: matrix.std >= 17
run: Release\flattests_cpp17.exe
build-windows:
name: Build Windows 2019
runs-on: windows-latest
permissions:
contents: write
outputs:
digests: ${{ steps.hash.outputs.hashes }}
name: Build Windows 2022
runs-on: windows-2022
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v6
- name: Add msbuild to PATH
uses: microsoft/setup-msbuild@v1.1
uses: microsoft/setup-msbuild@v2
- name: cmake
run: cmake -G "Visual Studio 16 2019" -A x64 -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_BUILD_CPP17=ON .
run: cmake -G "Visual Studio 17 2022" -A x64 -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_BUILD_CPP17=ON -DFLATBUFFERS_STRICT_MODE=ON .
- name: build
run: msbuild.exe FlatBuffers.sln /p:Configuration=Release /p:Platform=x64
- name: test
run: Release\flattests.exe
- name: upload build artifacts
uses: actions/upload-artifact@v1
uses: actions/upload-artifact@v4
with:
name: Windows flatc binary
path: Release\flatc.exe
build-windows-2017:
name: Build Windows 2017
runs-on: windows-latest
steps:
- uses: actions/checkout@v2
- name: Add msbuild to PATH
uses: microsoft/setup-msbuild@v1.1
- name: cmake
run: cmake -G "Visual Studio 16 2019" -A x64 -DCMAKE_BUILD_TYPE=Release .
- name: build tool version 15 (VS 2017)
run: msbuild.exe FlatBuffers.sln /p:Configuration=Release /p:Platform=x64 /p:VisualStudioVersion=15.0
- name: test
run: Release\flattests.exe
build-windows-2015:
name: Build Windows 2015
runs-on: windows-latest
steps:
- uses: actions/checkout@v2
- name: Add msbuild to PATH
uses: microsoft/setup-msbuild@v1.1
- name: cmake
run: cmake -G "Visual Studio 14 2015" -A x64 -DCMAKE_BUILD_TYPE=Release .
- name: build tool version 14 (VS 2015)
run: msbuild.exe FlatBuffers.sln /p:Configuration=Release /p:Platform=x64 /p:VisualStudioVersion=14.0
- name: test
run: Release\flattests.exe
# Below if only for release.
- name: Zip file
if: startsWith(github.ref, 'refs/tags/')
run: move Release/flatc.exe . && Compress-Archive flatc.exe Windows.flatc.binary.zip
- name: Release binary
uses: softprops/action-gh-release@v2
if: startsWith(github.ref, 'refs/tags/')
with:
files: Windows.flatc.binary.zip
- name: Generate SLSA subjects
if: startsWith(github.ref, 'refs/tags/')
id: hash
shell: bash
run: echo "hashes=$(sha256sum Windows.flatc.binary.zip | base64 -w0)" >> $GITHUB_OUTPUT
build-dotnet-windows:
name: Build .NET Windows
runs-on: windows-latest
runs-on: windows-2022-64core
strategy:
matrix:
configuration: [
'',
'-p:UnsafeByteBuffer=true',
# Fails two tests currently.
#'-p:EnableSpanT=true,UnsafeByteBuffer=true'
'-p:UnsafeByteBuffer=true',
'-p:EnableSpanT=true,UnsafeByteBuffer=true'
]
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v6
- name: Setup .NET Core SDK
uses: actions/setup-dotnet@v1.9.0
with:
dotnet-version: '3.1.x'
uses: actions/setup-dotnet@v5
with:
dotnet-version: '8.0.x'
- name: Build
run: |
cd tests\FlatBuffers.Test
dotnet new sln --force --name FlatBuffers.Core.Test
dotnet sln FlatBuffers.Core.Test.sln add FlatBuffers.Core.Test.csproj
dotnet build -c Release ${{matrix.configuration}} -o out FlatBuffers.Core.Test.sln
- name: Run
dotnet new sln --force --name FlatBuffers.Test --format sln
dotnet sln FlatBuffers.Test.sln add FlatBuffers.Test.csproj
dotnet build -c Release ${{matrix.configuration}} FlatBuffers.Test.sln
- name: Run net6.0
run: |
cd tests\FlatBuffers.Test
out\FlatBuffers.Core.Test.exe
cd tests\FlatBuffers.Test\bin\Release\net6.0
dir
.\FlatBuffers.Test.exe
- name: Run net8.0
run: |
cd tests\FlatBuffers.Test\bin\Release\net8.0
.\FlatBuffers.Test.exe
build-mac:
name: Build Mac
runs-on: macos-latest
build-mac-intel:
permissions:
contents: write
outputs:
digests: ${{ steps.hash.outputs.hashes }}
name: Build Mac (for Intel)
runs-on: macos-15-intel
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v6
- name: cmake
run: cmake -G "Xcode" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_FLATC_EXECUTABLE=_build/Release/flatc .
run: cmake -G "Xcode" -DCMAKE_OSX_ARCHITECTURES="x86_64" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON .
- name: build
# NOTE: we need this _build dir to not have xcodebuild's default ./build dir clash with the BUILD file.
run: xcodebuild -toolchain clang -configuration Release -target flattests SYMROOT=$(PWD)/_build
- name: check that the binary is "universal"
run: xcodebuild -toolchain clang -configuration Release -target flattests
- name: check that the binary is x86_64
run: |
info=$(file _build/Release/flatc)
info=$(file Release/flatc)
echo $info
echo $info | grep "universal binary with 2 architectures"
echo $info | grep "Mach-O 64-bit executable x86_64"
- name: test
run: _build/Release/flattests
run: Release/flattests
- name: make flatc executable
run: |
chmod +x _build/Release/flatc
./_build/Release/flatc --version
chmod +x Release/flatc
Release/flatc --version
- name: upload build artifacts
uses: actions/upload-artifact@v1
uses: actions/upload-artifact@v4
with:
name: Mac flatc binary
path: _build/Release/flatc
name: Mac flatc binary Intel
path: Release/flatc
# Below if only for release.
- name: Zip file
if: startsWith(github.ref, 'refs/tags/')
run: mv Release/flatc . && zip MacIntel.flatc.binary.zip flatc
- name: Release binary
uses: softprops/action-gh-release@v2
if: startsWith(github.ref, 'refs/tags/')
with:
files: MacIntel.flatc.binary.zip
- name: Generate SLSA subjects
if: startsWith(github.ref, 'refs/tags/')
id: hash
run: echo "hashes=$(shasum -a 256 MacIntel.flatc.binary.zip | base64)" >> $GITHUB_OUTPUT
build-mac-universal:
permissions:
contents: write
outputs:
digests: ${{ steps.hash.outputs.hashes }}
name: Build Mac (universal build)
runs-on: macos-latest
steps:
- uses: actions/checkout@v6
- name: cmake
run: cmake -G "Xcode" -DCMAKE_OSX_ARCHITECTURES="arm64;x86_64" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON .
- name: build
run: xcodebuild -toolchain clang -configuration Release -target flattests
- name: check that the binary is "universal"
run: |
info=$(file Release/flatc)
echo $info
echo $info | grep "Mach-O universal binary with 2 architectures"
- name: test
run: Release/flattests
- name: make flatc executable
run: |
chmod +x Release/flatc
Release/flatc --version
- name: upload build artifacts
uses: actions/upload-artifact@v4
with:
name: Mac flatc binary Universal
path: Release/flatc
# Below if only for release.
- name: Zip file
if: startsWith(github.ref, 'refs/tags/')
run: mv Release/flatc . && zip Mac.flatc.binary.zip flatc
- name: Release binary
uses: softprops/action-gh-release@v2
if: startsWith(github.ref, 'refs/tags/')
with:
files: Mac.flatc.binary.zip
- name: Generate SLSA subjects
if: startsWith(github.ref, 'refs/tags/')
id: hash
run: echo "hashes=$(shasum -a 256 Mac.flatc.binary.zip | base64)" >> $GITHUB_OUTPUT
build-android:
name: Build Android (on Linux)
runs-on: ubuntu-latest
if: false #disabled due to continual failure
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v2
- name: set up JDK 1.8
uses: actions/setup-java@v1
- uses: actions/checkout@v6
- name: set up Java
uses: actions/setup-java@v4
with:
java-version: 1.8
distribution: temurin
java-version: 17
- name: set up Gradle
uses: gradle/actions/setup-gradle@v5
- name: set up flatc
run: |
cmake -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF .
make
cmake -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF -DFLATBUFFERS_STRICT_MODE=ON .
make -j
echo "${PWD}" >> $GITHUB_PATH
- name: build
working-directory: android
run: bash ./gradlew clean build
run: gradle clean build
build-generator:
name: Check Generated Code
runs-on: ubuntu-latest
runs-on: ubuntu-24.04
strategy:
matrix:
cxx: [g++-10, clang++-12]
cxx: [g++-13, clang++-18]
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v6
- name: cmake
run: CXX=${{ matrix.cxx }} cmake -G "Unix Makefiles" -DFLATBUFFERS_BUILD_TESTS=OFF -DCMAKE_BUILD_TYPE=Release . && make -j4
run: CXX=${{ matrix.cxx }} cmake -G "Unix Makefiles" -DFLATBUFFERS_BUILD_TESTS=OFF -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON . && make -j
- name: Generate
run: scripts/check_generate_code.py
- name: Generate gRPC
run: bash scripts/check-grpc-generated-code.sh
run: scripts/check-grpc-generated-code.py
build-generator-windows:
name: Check Generated Code on Windows
runs-on: windows-2022
steps:
- uses: actions/checkout@v6
- name: Add msbuild to PATH
uses: microsoft/setup-msbuild@v2
- name: cmake
run: cmake -G "Visual Studio 17 2022" -A x64 -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_BUILD_CPP17=ON -DFLATBUFFERS_STRICT_MODE=ON .
- name: build
run: msbuild.exe FlatBuffers.sln /p:Configuration=Release /p:Platform=x64
- name: Generate
run: python3 scripts/check_generate_code.py --flatc Release\flatc.exe
- name: Generate gRPC
run: python3 scripts/check-grpc-generated-code.py --flatc Release\flatc.exe
build-benchmarks:
name: Build Benchmarks (on Linux)
runs-on: ubuntu-latest
runs-on: ubuntu-24.04
strategy:
matrix:
cxx: [g++-10]
cxx: [g++-13]
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v6
- name: cmake
run: CXX=${{ matrix.cxx }} cmake -G "Unix Makefiles" -DFLATBUFFERS_CXX_FLAGS="-Wno-unused-parameter -fno-aligned-new" -DFLATBUFFERS_BUILD_BENCHMARKS=ON -DCMAKE_BUILD_TYPE=Release . && make -j4
run: CXX=${{ matrix.cxx }} cmake -G "Unix Makefiles" -DFLATBUFFERS_CXX_FLAGS="-Wno-unused-parameter -fno-aligned-new" -DFLATBUFFERS_BUILD_BENCHMARKS=ON -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON . && make -j
- name: Run benchmarks
run: ./flatbenchmark --benchmark_repetitions=5 --benchmark_display_aggregates_only=true --benchmark_out_format=console --benchmark_out=benchmarks/results_${{matrix.cxx}}
- name: Upload benchmarks results
uses: actions/upload-artifact@v1
uses: actions/upload-artifact@v4
with:
name: Linux flatbenchmark results ${{matrix.cxx}}
path: benchmarks/results_${{matrix.cxx}}
build-java:
name: Build Java
runs-on: ubuntu-latest
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v6
- name: test
working-directory: tests
run: bash JavaTest.sh
working-directory: java
run: mvn test
build-kotlin-macos:
name: Build Kotlin MacOS
runs-on: macos-latest
runs-on: macos-15
steps:
- name: Checkout
uses: actions/checkout@v2
- uses: actions/setup-java@v2
uses: actions/checkout@v6
- name: set up Java
uses: actions/setup-java@v4
with:
distribution: 'adopt-hotspot'
java-version: '11'
distribution: temurin
java-version: 17
- name: set up Gradle
uses: gradle/actions/setup-gradle@v5
- name: Build flatc
run: |
cmake -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF .
make -j
echo "${PWD}" >> $GITHUB_PATH
- name: Build
working-directory: kotlin
run: ./gradlew clean iosX64Test macosX64Test jsTest jsBrowserTest
run: ./gradlew clean iosSimulatorArm64Test macosX64Test macosArm64Test
build-kotlin-linux:
name: Build Kotlin Linux
runs-on: ubuntu-latest
if: false #disabled due to continual failure
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v2
- uses: actions/setup-java@v2
uses: actions/checkout@v6
- name: set up Java
uses: actions/setup-java@v4
with:
distribution: 'adopt-hotspot'
java-version: '8'
distribution: temurin
java-version: 17
- name: set up Gradle
uses: gradle/actions/setup-gradle@v5
- name: Build flatc
run: |
cmake -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF .
make -j
echo "${PWD}" >> $GITHUB_PATH
- name: Build
working-directory: kotlin
run: ./gradlew jvmMainClasses jvmTest
- name: Run Benchmark
working-directory: kotlin
run: ./gradlew jvmBenchmark
- name: Generate Benchmark Report
working-directory: kotlin
run: |
./gradlew jmhReport;
mv benchmark/build/reports/benchmarks/main/* benchmark_latest
- name: Archive benchmark report
uses: actions/upload-artifact@v1
with:
name: Kotlin Benchmark Report
path: kotlin/benchmark_latest
# we are using docker's version of gradle
# so no need for wrapper validation or user
# gradlew
run: gradle jvmMainClasses jvmTest jsTest jsBrowserTest
build-rust:
name: Build Rust
runs-on: ubuntu-latest
build-rust-linux:
name: Build Rust Linux
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v6
- name: test
working-directory: tests
run: bash RustTest.sh
build-rust-windows:
name: Build Rust Windows
runs-on: windows-2022-64core
steps:
- uses: actions/checkout@v6
- name: test
working-directory: tests
run: ./RustTest.bat
build-python:
name: Build Python
runs-on: ubuntu-latest
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v6
- 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
build-go:
name: Build Go
runs-on: ubuntu-latest
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v6
- 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 . && make -j4
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 GoTest.sh
build-php:
name: Build PHP
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v6
- 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: |
php phpTest.php
sh phpUnionVectorTest.sh
build-swift:
name: Build Swift
runs-on: ubuntu-latest
name: Test Swift Linux
strategy:
matrix:
swift: ["5.10", "6.1", "6.2"]
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v6
- uses: swift-actions/setup-swift@v2
with:
swift-version: ${{ matrix.swift }}
- name: Get swift version
run: swift --version
- name: test
working-directory: tests/FlatBuffers.Test.Swift
run: sh SwiftTest.sh
run: swift test
build-swift-windows:
name: Test swift windows
runs-on: windows-latest
steps:
- uses: actions/checkout@v6
- uses: SwiftyLab/setup-swift@latest
with:
swift-version: '6.1'
- run: swift build
- run: swift test
build-swift-wasm:
name: Test Swift Wasm
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v6
- uses: swift-actions/setup-swift@v2
with:
swift-version: 6.2.1
- uses: bytecodealliance/actions/wasmtime/setup@v1
- name: Install Swift SDK
run: swift sdk install https://download.swift.org/swift-6.2.1-release/wasm-sdk/swift-6.2.1-RELEASE/swift-6.2.1-RELEASE_wasm.artifactbundle.tar.gz --checksum 482b9f95462b87bedfafca94a092cf9ec4496671ca13b43745097122d20f18af
- name: Test
working-directory: tests/swift/Wasm.tests
run: |
swift sdk list
swift build --build-tests --swift-sdk swift-6.2.1-RELEASE_wasm
wasmtime --dir . .build/wasm32-unknown-wasip1/debug/FlatBuffers.Test.Swift.WasmPackageTests.xctest
build-ts:
name: Build TS
runs-on: ubuntu-latest
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v6
- 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 . && make -j
- name: pnpm
run: npm install -g pnpm esbuild
- name: deps
run: pnpm i
- name: compile
run: npm run compile
run: pnpm compile
- name: test
working-directory: tests
run: sh TypeScriptTest.sh
working-directory: tests/ts
run: |
python3 TypeScriptTest.py
build-dart:
name: Build Dart
runs-on: ubuntu-latest
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v6
- uses: dart-lang/setup-dart@v1
with:
sdk: stable
- 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 . && make -j4
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 DartTest.sh
build-nim:
name: Build Nim
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v6
- 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 . && make -j
- uses: jiro4989/setup-nim-action@v2
- name: install library
working-directory: nim
run: nimble -y develop && nimble install
- name: test
working-directory: tests/nim
run: python3 testnim.py
bazel:
name: Bazel
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v6
# Explicitly use 8.5.1 until we can update or https://github.com/actions/runner-images/issues/13564 is fixed.
- name: Set env
run: >
echo "USE_BAZEL_VERSION=8.5.1" >> $GITHUB_ENV
- name: bazel build
run: >
bazel build
//:flatc
//:flatbuffers
//tests:flatbuffers_test
- name: bazel test
run: >
bazel test
//tests:flatbuffers_test
release-digests:
if: startsWith(github.ref, 'refs/tags/')
needs: [build-linux, build-windows, build-mac-intel, build-mac-universal]
outputs:
digests: ${{ steps.hash.outputs.digests }}
runs-on: ubuntu-24.04
steps:
- name: Merge results
id: hash
env:
LINUXGCC_DIGESTS: "${{ needs.build-linux.outputs.digests-gcc }}"
LINUXCLANG_DIGESTS: "${{ needs.build-linux.outputs.digests-clang }}"
MAC_DIGESTS: "${{ needs.build-mac-universal.outputs.digests }}"
MACINTEL_DIGESTS: "${{ needs.build-mac-intel.outputs.digests }}"
WINDOWS_DIGESTS: "${{ needs.build-windows.outputs.digests }}"
run: |
set -euo pipefail
echo "$LINUXGCC_DIGESTS" | base64 -d > checksums.txt
echo "$LINUXCLANG_DIGESTS" | base64 -d >> checksums.txt
echo "$MAC_DIGESTS" | base64 -d >> checksums.txt
echo "$MACINTEL_DIGESTS" | base64 -d >> checksums.txt
echo "$WINDOWS_DIGESTS" | base64 -d >> checksums.txt
echo "digests=$(cat checksums.txt | base64 -w0)" >> $GITHUB_OUTPUT
provenance:
if: startsWith(github.ref, 'refs/tags/')
needs: [release-digests]
permissions:
actions: read # To read the workflow path.
id-token: write # To sign the provenance.
contents: write # To add assets to a release.
uses: slsa-framework/slsa-github-generator/.github/workflows/generator_generic_slsa3.yml@v2.1.0
with:
base64-subjects: "${{ needs.release-digests.outputs.digests }}"
upload-assets: true # Optional: Upload to a new release

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

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

View File

@@ -6,14 +6,19 @@
# https://github.com/actions/labeler
name: Labeler
permissions: read-all
on: [pull_request_target]
jobs:
label:
permissions:
contents: read
pull-requests: write
runs-on: ubuntu-latest
steps:
- uses: actions/labeler@main
- uses: actions/labeler@v6
with:
repo-token: "${{ secrets.GITHUB_TOKEN }}"
repo-token: "${{ secrets.GITHUB_TOKEN }}"

View File

@@ -1,5 +1,15 @@
name: CIFuzz
on: [pull_request]
name: OSS-Fuzz
permissions: read-all
on:
pull_request:
branches:
- master
paths:
- include/**
- src/**
- tests/**.cpp
- tests/**.h
jobs:
Fuzzing:
runs-on: ubuntu-latest
@@ -15,9 +25,9 @@ jobs:
with:
oss-fuzz-project-name: 'flatbuffers'
language: c++
fuzz-seconds: 600
fuzz-seconds: 60
- name: Upload Crash
uses: actions/upload-artifact@v1
uses: actions/upload-artifact@v4
if: failure() && steps.build.outcome == 'success'
with:
name: artifacts

152
.github/workflows/release.yml vendored Normal file
View File

@@ -0,0 +1,152 @@
name: Release
permissions: read-all
on:
# For manual tests.
workflow_dispatch:
release:
types: [published]
jobs:
publish-npm:
name: Publish NPM
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v3
with:
node-version: '20.x'
registry-url: 'https://registry.npmjs.org'
- run: npm publish
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
publish-pypi:
name: Publish PyPi
runs-on: ubuntu-latest
defaults:
run:
working-directory: ./python
steps:
- uses: actions/checkout@v6
- uses: actions/setup-python@v4
with:
python-version: '3.10'
- name: Install Dependencies
run: |
python3 -m pip install --upgrade pip
python3 -m pip install build twine
- name: Build
run: |
python3 -m build .
- name: Upload to PyPi
run: |
python3 -m twine upload dist/*
env:
TWINE_USERNAME: __token__
TWINE_PASSWORD: ${{ secrets.TWINE_TOKEN }}
publish-nuget:
name: Publish NuGet
runs-on: windows-latest
defaults:
run:
working-directory: ./net/flatbuffers
steps:
- uses: actions/checkout@v6
- uses: actions/setup-dotnet@v5
with:
dotnet-version: '8.0.x'
- name: Build
run: |
dotnet build Google.FlatBuffers.csproj -c Release
- name: Pack
run: |
dotnet pack Google.FlatBuffers.csproj -c Release
- name: Upload to NuGet
run: |
dotnet nuget push .\bin\Release\Google.FlatBuffers.*.nupkg -k ${{ secrets.NUGET_API_KEY }} -s https://api.nuget.org/v3/index.json
publish-maven:
name: Publish Maven
runs-on: ubuntu-latest
defaults:
run:
working-directory: ./java
steps:
- uses: actions/checkout@v6
- name: Set up Maven Central Repository
uses: actions/setup-java@v5
with:
java-version: '11'
distribution: 'adopt'
cache: 'maven'
server-id: ossrh
server-username: OSSRH_USERNAME
server-password: OSSRH_PASSWORD
gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }}
gpg-passphrase: MAVEN_GPG_PASSPHRASE # this needs to be an env var
- name: Publish Maven
run: mvn --batch-mode clean deploy
env:
OSSRH_USERNAME: ${{ secrets.OSSRH_USER_V2 }}
OSSRH_PASSWORD: ${{ secrets.OSSRH_TOKEN_V2 }}
MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }}
publish-maven-kotlin:
name: Publish Maven - Kotlin
runs-on: ubuntu-latest
defaults:
run:
working-directory: ./kotlin
steps:
- uses: actions/checkout@v6
- name: Set up Maven Central Repository
uses: actions/setup-java@v5
with:
java-version: '11'
distribution: 'adopt'
cache: 'maven'
server-id: ossrh
server-username: OSSRH_USERNAME
server-password: OSSRH_PASSWORD
gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }}
gpg-passphrase: MAVEN_GPG_PASSPHRASE # this needs to be an env var
- name: Publish Kotlin Library on Maven
run: ./gradlew publishAllPublicationsToSonatypeRepository
env:
OSSRH_USERNAME: ${{ secrets.OSSRH_USER_V2 }}
OSSRH_PASSWORD: ${{ secrets.OSSRH_TOKEN_V2 }}
MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }}
publish-crates:
name: Publish crates.io
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
- name: Publish Flatbuffers
uses: katyo/publish-crates@v2
with:
path: ./rust/flatbuffers
registry-token: ${{ secrets.CARGO_TOKEN }}
- name: Publish Flexbuffers
uses: katyo/publish-crates@v2
with:
path: ./rust/flexbuffers
registry-token: ${{ secrets.CARGO_TOKEN }}

View File

@@ -1,8 +1,13 @@
name: Mark stale issues and pull requests
permissions:
issues: write
pull-requests: write
on:
# For manual tests.
workflow_dispatch:
schedule:
- cron: "30 20 * * *"
- cron: "30 20 * * *"
jobs:
stale:
@@ -10,14 +15,23 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v4.0.0
- uses: actions/stale@v10
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 6 months with no activity. Please comment or label `not-stale`, or this will be closed in 14 days.'
close-pr-message: 'This pull request was automatically closed due to no activity for 6 months plus the 14 day notice period.'
days-before-pr-stale: 182 # 6 months
days-before-pr-close: 14 # 2 week
exempt-pr-labels: not-stale
exempt-draft-pr: false

17
.gitignore vendored
View File

@@ -54,6 +54,8 @@ flathash
flathash.exe
flattests
flattests.exe
flattests_cpp17
flattests_cpp17.exe
flatsamplebinary
flatsamplebinary.exe
flatsampletext
@@ -76,7 +78,7 @@ tests/php/
CMakeLists.txt.user
CMakeScripts/**
CTestTestfile.cmake
FlatbuffersConfigVersion.cmake
flatbuffers-config-version.cmake
FlatBuffers.cbp
build/Xcode/FlatBuffers.xcodeproj/project.xcworkspace/**
build/Xcode/FlatBuffers.xcodeproj/xcuserdata/**
@@ -86,6 +88,7 @@ java/*.iml
.idea
*.iml
target
java/target
**/*.pyc
build/VS2010/FlatBuffers.sdf
build/VS2010/FlatBuffers.opensdf
@@ -146,4 +149,14 @@ flatbuffers.pc
**/html/**
**/latex/**
# https://cmake.org/cmake/help/latest/module/FetchContent.html#variable:FETCHCONTENT_BASE_DIR
_deps/
cmake-build-debug/
_deps/
**/.gradle/**
kotlin/**/generated
MODULE.bazel.lock
# Ignore the generated docs
docs/site
# Ignore generated files
*.fbs.h

1
.npmrc Normal file
View File

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

View File

@@ -1,215 +0,0 @@
env:
global:
# Set at the root level as this is ignored when set under matrix.env.
- GCC_VERSION="4.9"
# Fail on first error if UBSAN or ASAN enabled for a target
- UBSAN_OPTIONS=halt_on_error=1
- ASAN_OPTIONS=halt_on_error=1
# Travis machines have 2 cores
- JOBS=2
- MAKEFLAGS="-j 2"
conan-linux: &conan-linux
os: linux
dist: xenial
language: python
python: "3.7"
services:
- docker
install:
- ./conan/travis/install.sh
script:
- ./conan/travis/build.sh
if: tag IS present
conan-linux-master: &conan-linux-master
os: linux
dist: xenial
language: python
python: "3.7"
services:
- docker
install:
- 'if [ "$TRAVIS_PULL_REQUEST" = "false" ]; then bash ./conan/travis/install.sh; fi'
script:
- 'if [ "$TRAVIS_PULL_REQUEST" = "false" ]; then bash ./conan/travis/build.sh; fi'
branches:
only:
- master
conan-osx: &conan-osx
os: osx
language: generic
install:
- ./conan/travis/install.sh
script:
- ./conan/travis/build.sh
if: tag IS present
matrix:
include:
#- language: python
# python: "2.7"
# install:
# - "pip install wheel twine"
# script:
# - "cd python/"
# - 'VERSION="$TRAVIS_TAG" python setup.py sdist bdist_wheel'
# - "cd ../"
# deploy:
# # Checkpointed release builds.
# - provider: script
# script: .travis/deploy-python.sh
# skip_cleanup: true
# on:
# tags: true
# # all_branches must be set with tags: true. See below post:
# # https://stackoverflow.com/a/27775257/1076585
# all_branches: true
# # Produce a new build for the cutting edge when master changes.
# - provider: script
# script: .travis/deploy-python.sh
# skip_cleanup: true
# on:
# branch: master
- language: cpp
os:
- linux
addons:
apt:
packages:
- docker-ce
script:
- bash .travis/build-and-run-docker-test-containers.sh
- language: cpp
os:
- linux
compiler:
- gcc
env:
matrix:
- BUILD_TYPE=Debug
- BUILD_TYPE=Release
before_install:
- if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test; fi
- if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo apt-get update -qq; fi
- if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo apt-get install -qq g++-$GCC_VERSION; fi
- if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo apt-get install -qq gcc-$GCC_VERSION; fi
- if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo ln -s -v -f $(which g++-$GCC_VERSION) /usr/bin/g++; fi
- if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo ln -s -v -f $(which gcc-$GCC_VERSION) /usr/bin/gcc; fi
script:
- pip install cmake
- bash .travis/check-sources.sh
- bash grpc/build_grpc.sh
- cmake .
-DCMAKE_BUILD_TYPE=$BUILD_TYPE
-DFLATBUFFERS_BUILD_GRPCTEST=ON
-DGRPC_INSTALL_PATH=$TRAVIS_BUILD_DIR/google/grpc/install
-DPROTOBUF_DOWNLOAD_PATH=$TRAVIS_BUILD_DIR/google/grpc/third_party/protobuf
-DFLATBUFFERS_CODE_SANITIZE=ON
- cmake --build . --target all --clean-first -- -j${JOBS}
- LD_LIBRARY_PATH=$TRAVIS_BUILD_DIR/google/grpc/install/lib ctest --extra-verbose --output-on-failure
- language: cpp
os: osx
osx_image: xcode9.3
env:
matrix:
- BUILD_TYPE=Debug
- BUILD_TYPE=Release
script:
- pip install --user cmake
- mkdir ~/cmake_path
- ln -s $(find ~/Library/Python -name cmake -type f | head -n 1) ~/cmake_path/cmake
- ln -s $(find ~/Library/Python -name ctest -type f | head -n 1) ~/cmake_path/ctest
- export PATH=~/cmake_path:${PATH}
- bash grpc/build_grpc.sh
- cmake .
-DCMAKE_BUILD_TYPE=$BUILD_TYPE
-DFLATBUFFERS_BUILD_GRPCTEST=ON
-DGRPC_INSTALL_PATH=$TRAVIS_BUILD_DIR/google/grpc/install
-DPROTOBUF_DOWNLOAD_PATH=$TRAVIS_BUILD_DIR/google/grpc/third_party/protobuf
-DFLATBUFFERS_CODE_SANITIZE=ON
- cmake --build . -- -j${JOBS}
- DYLD_LIBRARY_PATH=$TRAVIS_BUILD_DIR/google/grpc/install/lib ctest --extra-verbose --output-on-failure
- <<: *conan-linux-master
env: CONAN_GCC_VERSIONS=8 CONAN_DOCKER_IMAGE=conanio/gcc8
- <<: *conan-linux
env: CONAN_GCC_VERSIONS=4.9 CONAN_DOCKER_IMAGE=conanio/gcc49
- <<: *conan-linux
env: CONAN_GCC_VERSIONS=5 CONAN_DOCKER_IMAGE=conanio/gcc5
- <<: *conan-linux
env: CONAN_GCC_VERSIONS=6 CONAN_DOCKER_IMAGE=conanio/gcc6
- <<: *conan-linux
env: CONAN_GCC_VERSIONS=7 CONAN_DOCKER_IMAGE=conanio/gcc7
- <<: *conan-linux
env: CONAN_GCC_VERSIONS=8 CONAN_DOCKER_IMAGE=conanio/gcc8
- <<: *conan-linux
env: CONAN_GCC_VERSIONS=9 CONAN_DOCKER_IMAGE=conanio/gcc9
- <<: *conan-linux
env: CONAN_CLANG_VERSIONS=3.9 CONAN_DOCKER_IMAGE=conanio/clang39
- <<: *conan-linux
env: CONAN_CLANG_VERSIONS=4.0 CONAN_DOCKER_IMAGE=conanio/clang40
- <<: *conan-linux
env: CONAN_CLANG_VERSIONS=5.0 CONAN_DOCKER_IMAGE=conanio/clang50
- <<: *conan-linux
env: CONAN_CLANG_VERSIONS=6.0 CONAN_DOCKER_IMAGE=conanio/clang60
- <<: *conan-linux
env: CONAN_CLANG_VERSIONS=7.0 CONAN_DOCKER_IMAGE=conanio/clang7
- <<: *conan-linux
env: CONAN_CLANG_VERSIONS=8 CONAN_DOCKER_IMAGE=conanio/clang8
- <<: *conan-osx
osx_image: xcode7.3
env: CONAN_APPLE_CLANG_VERSIONS=7.3
- <<: *conan-osx
osx_image: xcode8.3
env: CONAN_APPLE_CLANG_VERSIONS=8.1
- <<: *conan-osx
osx_image: xcode9
env: CONAN_APPLE_CLANG_VERSIONS=9.0
- <<: *conan-osx
osx_image: xcode9.4
env: CONAN_APPLE_CLANG_VERSIONS=9.1
- <<: *conan-osx
osx_image: xcode10.2
env: CONAN_APPLE_CLANG_VERSIONS=10.0
- language: android
sudo: true
dist: trusty
android:
components:
- tools
- platform-tools
- extra-android-m2repository
licenses:
- 'android-sdk-preview-license-52d11cd2'
- 'android-sdk-license-.+'
- 'google-gdk-license-.+'
compiler:
- gcc
before_install:
- echo y | sdkmanager "platforms;android-30"
- echo y | sdkmanager "build-tools;30.0.2"
- echo y | sdkmanager "ndk-bundle"
- echo y | sdkmanager "cmake;3.6.4111459"
script:
- cmake -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF .; make; export PATH="$PATH:${PWD}"
- cd android; ./gradlew clean build
- language: generic
if: type IN (pull_request)
os: linux
install:
- bash .travis/format_install.sh
script:
- bash .travis/format_check.sh

View File

@@ -1,45 +0,0 @@
#!/bin/bash
#
# Copyright 2018 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
set -e
docker build -t build_cpp_image -f tests/docker/Dockerfile.testing.cpp.debian_buster .
# Run tests with sanitizers (--cap-add SYS_PTRACE), both GCC and Clang.
cpp_test_args="--cap-add SYS_PTRACE build_cpp_image sh ./tests/docker/cpp_test.run.sh Debug"
docker run --rm $cpp_test_args
docker run --rm --env CC=/usr/bin/clang --env CXX=/usr/bin/clang++ $cpp_test_args
# Build flatc on debian once to speed up the test loop below.
docker run --name flatc_container build_cpp_image sh ./tests/docker/build_flatc.run.sh Debug
# All dependent dockers refer to 'flatc_debian_stretch'.
docker cp flatc_container:/flatbuffers/flatc flatc_debian_stretch
for f in $(ls tests/docker/languages | sort)
do
# docker pull sometimes fails for unknown reasons, probably travisci-related. this retries the pull we need a few times.
REQUIRED_BASE_IMAGE=$(cat tests/docker/languages/${f} | head -n 1 | awk ' { print $2 } ')
set +e
n=0
until [ $n -ge 5 ]
do
docker pull $REQUIRED_BASE_IMAGE && break
n=$[$n+1]
sleep 1
done
set -e
docker build -t $(echo ${f} | cut -f 3- -d .) -f tests/docker/languages/${f} .
echo "TEST OK: ${f}"
done

View File

@@ -1,33 +0,0 @@
#!/bin/bash
#
# Copyright 2018 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
set -e
if [ -n "$1" ]; then
scan_dir="$1"
else
scan_dir="$( pwd )"
fi
py_checker="$0.py"
echo "scan root directory = '$scan_dir'"
python3 --version
# Scan recursively and search all *.cpp and *.h files using regex patterns.
# Assume that script running from a root of Flatbuffers working dir.
python3 $py_checker "ascii" "$scan_dir/include" "\.h$"
python3 $py_checker "ascii" "$scan_dir/src" "\.cpp$"
python3 $py_checker "ascii" "$scan_dir/tests" "\.h$"
python3 $py_checker "utf-8" "$scan_dir/tests" "\.cpp$"

View File

@@ -1,35 +0,0 @@
import os
import re
import sys
def check_encoding(encoding, scan_dir, regex_pattern):
fname = None
try:
assert encoding in ['ascii', 'utf-8'], "unexpected encoding"
cmp = re.compile(regex_pattern)
for root, dirs, files in os.walk(scan_dir):
fname = root
cmp_list = [f for f in files if cmp.search(f) is not None]
for f in cmp_list:
fname = os.path.join(root, f)
with open(fname, mode='rb') as test_file:
btext = test_file.read()
# check encoding
btext.decode(encoding=encoding, errors="strict")
if encoding == "utf-8" and btext.startswith(b'\xEF\xBB\xBF'):
raise ValueError("unexpected BOM in file")
# check LF line endings
LF = btext.count(b'\n')
CR = btext.count(b'\r')
if CR!=0:
raise ValueError("invalid line endings: LF({})/CR({})".format(LF, CR))
except Exception as err:
print("ERROR with [{}]: {}".format(fname, err))
return -1
else:
return 0
if __name__ == "__main__":
# python check-sources.sh.py 'ascii' '.' '.*\.(cpp|h)$'
res = check_encoding(sys.argv[1], sys.argv[2], sys.argv[3])
sys.exit(0 if res == 0 else -1)

View File

@@ -1,12 +0,0 @@
#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROD_REPOSITORY="https://upload.pypi.org/legacy/"
TEST_REPOSITORY="https://test.pypi.org/legacy/"
twine upload \
--username "$PYPI_USERNAME" \
--password "$PYPI_PASSWORD" \
--repository-url "$PROD_REPOSITORY" \
"$DIR/../python/dist/"*

View File

@@ -1,52 +0,0 @@
#!/bin/bash
#
# Copyright 2021 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.
set -e
# HACKY solution to make nodejs work.
source ~/.nvm/nvm.sh
nvm alias default node
nvm use default
sh scripts/clang-format-git.sh
# Check formatting for go lang
cd go
gofmt -w .
cd ..
cd grpc/examples/go
sh format.sh
cd ../../..
node_modules/.bin/eslint ts/** --ext .ts --quiet --fix
#PYTHON IS DISABLED UNTIL WE CREATE A .pylintrc FILE FOR IT
pylint python/** --disable=all
swiftformat --config swift.swiftformat .
if ! git diff --quiet; then
echo >&2
echo "ERROR: ********************************************************" >&2
echo "ERROR: The following differences were found after running" >&2
echo "ERROR: .travis/format_check.sh script. Maybe you forgot to format" >&2
echo "ERROR: the code after making changes? please check Formatters.md" >&2
echo "ERROR: ********************************************************" >&2
echo >&2
git diff --binary --exit-code
fi

View File

@@ -1,90 +0,0 @@
#!/bin/bash
#
# Copyright 2020 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
set -e
set -x
# install devtools
install_languages() {
sudo apt update
# Install nodeJS and yarn
wget https://raw.githubusercontent.com/creationix/nvm/v0.31.0/nvm.sh -O ~/.nvm/nvm.sh
source ~/.nvm/nvm.sh
nvm install node
node --version
curl -o- -L https://yarnpkg.com/install.sh | bash
export PATH="$HOME/.yarn/bin:$PATH"
yarn config set prefix ~/.yarn -g
export PATH="$HOME/.yarn/bin:$HOME/.config/yarn/global/node_modules/.bin:$PATH"
# Install swift
sudo apt-get install \
binutils \
git \
libc6-dev \
libcurl3 \
libedit2 \
libgcc-5-dev \
libpython2.7 \
libsqlite3-0 \
libstdc++-5-dev \
libxml2 \
pkg-config \
tzdata \
zlib1g-dev
SWIFT_URL=https://swift.org/builds/swift-5.3.1-release/ubuntu1604/swift-5.3.1-RELEASE/swift-5.3.1-RELEASE-ubuntu16.04.tar.gz
curl -fSsL "$SWIFT_URL" -o swift.tar.gz
mkdir ~/swiftbuild
tar -xvzf swift.tar.gz -C ~/swiftbuild
export PATH="~/swiftbuild/swift-5.3.1-RELEASE-ubuntu16.04/usr/bin:$PATH"
mkdir ~/gobuild
wget -c https://golang.org/dl/go1.15.2.linux-amd64.tar.gz
tar -xvzf go1.15.2.linux-amd64.tar.gz -C ~/gobuild
export PATH="~/gobuild/go/bin:$PATH"
swift --version
go version
yarn -v
node -v
}
install_formatters() {
# installing swift formatter
git clone --depth 1 --branch 0.47.4 https://github.com/nicklockwood/SwiftFormat.git
cd SwiftFormat
swift build -c release
sudo cp .build/release/swiftformat /usr/local/bin/swiftformat
cd ..
which yarn
which node
yarn -v
node -v
yarn install
pip install pylint
}
install_languages
export PATH="~/swift/swift/usr/bin:$PATH"
install_formatters

View File

@@ -8,6 +8,7 @@ package(
exports_files([
"LICENSE",
"tsconfig.json",
])
config_setting(
@@ -24,6 +25,28 @@ config_setting(
],
)
filegroup(
name = "distribution",
srcs = [
".bazelignore",
".npmrc",
"BUILD.bazel",
"MODULE.bazel",
"build_defs.bzl",
"package.json",
"pnpm-lock.yaml",
"typescript.bzl",
"//grpc/src/compiler:distribution",
"//include/codegen:distribution",
"//reflection:distribution",
"//src:distribution",
"//ts:distribution",
] + glob([
"include/flatbuffers/*.h",
]),
visibility = ["//visibility:public"],
)
# Public flatc library to compile flatbuffer files at runtime.
cc_library(
name = "flatbuffers",
@@ -40,14 +63,16 @@ 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",
"include/flatbuffers/flexbuffers.h",
"include/flatbuffers/grpc.h",
"include/flatbuffers/hash.h",
@@ -79,6 +104,7 @@ cc_library(
# Public flatc compiler.
cc_binary(
name = "flatc",
data = ["//reflection:reflection_fbs_schema"],
deps = [
"//src:flatc",
],
@@ -95,15 +121,7 @@ filegroup(
# Library used by flatbuffer_cc_library rules.
cc_library(
name = "runtime_cc",
hdrs = [
"include/flatbuffers/base.h",
"include/flatbuffers/flatbuffers.h",
"include/flatbuffers/flexbuffers.h",
"include/flatbuffers/stl_emulation.h",
"include/flatbuffers/util.h",
"include/flatbuffers/vector.h",
"include/flatbuffers/verifier.h",
],
hdrs = ["//:public_headers"],
linkstatic = 1,
strip_include_prefix = "/include",
)

201
CHANGELOG.md Normal file
View File

@@ -0,0 +1,201 @@
# Flatbuffers Change Log
All major or breaking changes will be documented in this file, as well as any
new features that should be highlighted. Minor fixes or improvements are not
necessarily listed.
## [25.12.19] (December 19 2025)(https://github.com/google/flatbuffers/releases/tag/v25.12.19)
* [C++] Default emptry vector support (#8870)
* [C++] Add --gen-absl-hash option (#8868)
* [Kotlin] Upgrade to MacOS 15 (#8845)
* [C++] Fix vector of table with naked ptrs (#8830)
* [Python] Optimize Offset/Pad/Prep (#8808)
* Implement `--file-names-only` (#8788)
* [C++] Fix size verifer (#8740)
## [25.9.23] (September 23 2025)(https://github.com/google/flatbuffers/releases/tag/v25.9.23)
* flatc: `--grpc-callback-api` flag generates C++ gRPC Callback API server `CallbackService` skeletons AND client native callback/async stubs (unary + all streaming reactor forms) (opt-in, non-breaking, issue #8596).
* Swift - Adds new API to reduce memory copying within swift (#8484)
* Rust - Support Rust edition 2024 (#8638)
* [C++] - Use the Google Style for clang-format without exceptions (#8706)
## [25.2.10] (February 10 2025)(https://github.com/google/flatbuffers/releases/tag/v25.2.10)
* Removed the old documentation pages. The new one is live at https://flatbuffers.dev
* Swift version 6.0 support (#8414)
## [25.1.24] (January 24 2025)(https://github.com/google/flatbuffers/releases/tag/v25.1.24)
* Mostly related to bazel build support.
* Min bazel supported is now 7 or higher, as WORKSPACE files are removed (#8509)
* Minor C++ codegen fix removing extra semicolon (#8488)
## [25.1.21] (January 21 2025)(https://github.com/google/flatbuffers/releases/tag/v25.1.21)
* Rust Full Reflection (#8102)
* Mostly documentation updates hosted at https://flatbuffers.dev
## [24.3.25] (March 25 2024)(https://github.com/google/flatbuffers/releases/tag/v24.3.25)
* Fixed license metadata parsing (#8253)
* [C++] Allow string_view in `LookUpByKey` in addition to null-terminated c-style strings (#8203)
## [24.3.7] (March 7 2024)(https://github.com/google/flatbuffers/releases/tag/v24.3.7)
* Just to fix some of the CI build issues from the 24.3.6 release.
## [24.3.6] (March 6 2024)(https://github.com/google/flatbuffers/releases/tag/v24.3.6)
* Fix typescript object API to allow 0 values for null-default scalars (#7864)
## [23.5.26 (May 26 2023)](https://github.com/google/flatbuffers/releases/tag/v23.5.26)
* Mostly bug fixing for 64-bit support
* 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
file build (#7510)
## [23.1.20 (Jan 20 2023)](https://github.com/google/flatbuffers/releases/tag/v23.1.20)
* Removed go.mod files after some versioning issues were being report (#7780).
## [23.1.4 (Jan 4 2023)](https://github.com/google/flatbuffers/releases/tag/v23.1.4)
* Major release! Just kidding, we are continuing the
[versioning scheme](https://github.com/google/flatbuffers/wiki/Versioning) of
using a date to signify releases. This results in the first release of the new
year to bump the tradition major version field.
* Go minimum version is now 1.19 (#7720) with the addition of Go modules.
* Added CI support for Big Endian regression testing (#7707).
* Fixed `getFullyQualifiedName` in typescript to return name delimited by '.'
instead of '_' (#7730).
* Fixed the versioning scheme to not include leading zeros which are not
consistently handled by every package manager. Only the last release
(12.12.06) should have suffered from this.
## [22.12.06 (Dec 06 2022)](https://github.com/google/flatbuffers/releases/tag/v22.12.06)
* Bug fixing release, no major changes.
## [22.10.25 (Oct 25 2022)](https://github.com/google/flatbuffers/releases/tag/v22.10.25)
* Added Nim language support with generator and runtime libraries (#7534).
## [22.9.29 (Sept 29 2022)](https://github.com/google/flatbuffers/releases/tag/v22.9.29)
* Rust soundness fixes to avoid the crate from bing labelled unsafe (#7518).
## [22.9.24 (Sept 24 2022)](https://github.com/google/flatbuffers/releases/tag/v22.9.24)
* 20 Major releases in a row? Nope, we switched to a new
[versioning scheme](https://github.com/google/flatbuffers/wiki/Versioning)
that is based on date.
* Python supports fixed size arrays now (#7529).
* Behavior change in how C++ object API uses `UnPackTo`. The original intent of
this was to reduce allocations by reusing an existing object to pack data
into. At some point, this logic started to merge the states of the two objects
instead of clearing the state of the packee. This change goes back to the
original intention, the packed object is cleared when getting data packed into
it (#7527).
* Fixed a bug in C++ alignment that was using `sizeof()` instead of the intended
`AlignOf()` for structs (#7520).
* C# has an
[official Nuget package](https://www.nuget.org/packages/Google.FlatBuffers)
now (#7496).
## 2.0.8 (Aug 29 2022)
* Fix for `--keep-prefix` the was generating the wrong include statements for
C++ (#7469). The bug was introduced in 2.0.7.
* Added the `Verifier::Options` option struct to allow specifying runtime
configuration settings for the verifier (#7489). This allows to skip verifying
nested flatbuffers, a on-by-default change that was introduced in 2.0.7. This
deprecates the existing `Verifier` constructor, which may be removed in a
future version.
* Refactor of `tests/test.cpp` that lead to ~10% speedup in compilation of the
entire project (#7487).
## 2.0.7 (Aug 22 2022)
* This is the first version with an explicit change log, so all the previous
features will not be listed.
* Verifier now checks that buffers are at least the minimum size required to be
a flatbuffers (12 bytes). This includes nested flatbuffers, which previously
could be declared valid at size 0.
* Annotated binaries. Given a flatbuffer binary and a schema (or binary schema)
one can generate an annotated flatbuffer (.afb) to describe each byte in the
binary with schema metadata and value.
* First binary schema generator (Lua) to generate Lua code via a .bfbs file.
This is mostly an implementation detail of flatc internals, but will be slowly
applied to the other language generators.

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(
@@ -282,8 +305,7 @@ function(flatbuffers_generate_headers)
${FLATBUFFERS_GENERATE_HEADERS_SCHEMAS})
add_dependencies(
${FLATBUFFERS_GENERATE_HEADERS_TARGET}
${FLATC}
${FLATBUFFERS_GENERATE_HEADERS_SCHEMAS})
${FLATC_TARGET})
target_include_directories(
${FLATBUFFERS_GENERATE_HEADERS_TARGET}
INTERFACE ${generated_target_dir})
@@ -365,6 +387,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,774 +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)
project(FlatBuffers
DESCRIPTION "Flatbuffers serialization library"
VERSION 2.0.0
LANGUAGES CXX)
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})
# Shared object version: "major.minor.micro"
# - micro updated every release when there is no API/ABI changes
# - minor updated when there are additions in API/ABI
# - major (ABI number) updated when there are changes in ABI (or removals)
set(FlatBuffers_Library_SONAME_MAJOR ${VERSION_MAJOR})
set(FlatBuffers_Library_SONAME_FULL "${FlatBuffers_Library_SONAME_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}")
set_target_properties(flatbuffers_shared PROPERTIES OUTPUT_NAME flatbuffers
SOVERSION "${FlatBuffers_Library_SONAME_MAJOR}"
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/FlatbuffersConfigVersion.cmake.in FlatbuffersConfigVersion.cmake @ONLY)
install(
FILES "CMake/FlatbuffersConfig.cmake" "${CMAKE_CURRENT_BINARY_DIR}/FlatbuffersConfigVersion.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

@@ -1,4 +0,0 @@
include("${CMAKE_CURRENT_LIST_DIR}/FlatbuffersTargets.cmake" OPTIONAL)
include("${CMAKE_CURRENT_LIST_DIR}/FlatcTargets.cmake" OPTIONAL)
include("${CMAKE_CURRENT_LIST_DIR}/FlatbuffersSharedTargets.cmake" OPTIONAL)

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,28 +1,39 @@
set(VERSION_MAJOR 2)
set(VERSION_MINOR 0)
set(VERSION_PATCH 6)
set(VERSION_MAJOR 25)
set(VERSION_MINOR 12)
set(VERSION_PATCH 19)
set(VERSION_COMMIT 0)
find_program(GIT git)
if(GIT AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/.git")
execute_process(
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/.git")
find_program(GIT git)
if(GIT)
execute_process(
COMMAND ${GIT} describe --tags
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
OUTPUT_VARIABLE GIT_DESCRIBE_DIRTY
OUTPUT_STRIP_TRAILING_WHITESPACE
RESULT_VARIABLE GIT_DESCRIBE_RESULT
)
)
if(GIT_DESCRIBE_RESULT EQUAL 0)
string(REGEX REPLACE "^v([0-9]+)\\..*" "\\1" VERSION_MAJOR "${GIT_DESCRIBE_DIRTY}")
string(REGEX REPLACE "^v[0-9]+\\.([0-9]+).*" "\\1" VERSION_MINOR "${GIT_DESCRIBE_DIRTY}")
string(REGEX REPLACE "^v[0-9]+\\.[0-9]+\\.([0-9]+).*" "\\1" VERSION_PATCH "${GIT_DESCRIBE_DIRTY}")
string(REGEX REPLACE "^v[0-9]+\\.[0-9]+\\.[0-9]+\\-([0-9]+).*" "\\1" VERSION_COMMIT "${GIT_DESCRIBE_DIRTY}")
if(GIT_DESCRIBE_RESULT EQUAL 0)
# Test if the most recent Git tag matches the pattern "v<major>.<minor>.<patch>*"
if(GIT_DESCRIBE_DIRTY MATCHES "^v[0-9]+\\.[0-9]+\\.[0-9]+.*")
string(REGEX REPLACE "^v([0-9]+)\\..*" "\\1" VERSION_MAJOR "${GIT_DESCRIBE_DIRTY}")
string(REGEX REPLACE "^v[0-9]+\\.([0-9]+).*" "\\1" VERSION_MINOR "${GIT_DESCRIBE_DIRTY}")
string(REGEX REPLACE "^v[0-9]+\\.[0-9]+\\.([0-9]+).*" "\\1" VERSION_PATCH "${GIT_DESCRIBE_DIRTY}")
string(REGEX REPLACE "^v[0-9]+\\.[0-9]+\\.[0-9]+\\-([0-9]+).*" "\\1" VERSION_COMMIT "${GIT_DESCRIBE_DIRTY}")
# If the tag points to the commit, then only the tag is shown in "git describe"
if(VERSION_COMMIT STREQUAL GIT_DESCRIBE_DIRTY)
set(VERSION_COMMIT 0)
endif()
else()
message(WARNING "\"${GIT_DESCRIBE_DIRTY}\" does not match pattern v<major>.<minor>.<patch>-<commit>")
endif()
else()
message(WARNING "git describe failed with exit code: ${GIT_DESCRIBE_RESULT}\nMake sure you cloned with tags or run 'git fetch --tags'.")
endif()
else()
message(WARNING "git describe failed with exit code: ${GIT_DESCRIBE_RESULT}")
message(WARNING "git is not found")
endif()
else()
message(WARNING "git is not found")
endif()
message(STATUS "Proceeding with version: ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}.${VERSION_COMMIT}")

View File

@@ -0,0 +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,13 @@
# This is the legacy minimum version flatbuffers supported for a while.
cmake_minimum_required(VERSION 2.8.12)
# 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()
if (POLICY CMP0048)
cmake_policy(SET CMP0048 NEW)
project(FlatBuffers
DESCRIPTION "Flatbuffers serialization library"
VERSION 2.0.0
LANGUAGES CXX)
else()
project(FlatBuffers)
endif (POLICY CMP0048)
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)
project(FlatBuffers
VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}
LANGUAGES CXX)
# generate compile_commands.json
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
@@ -40,9 +21,8 @@ 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."
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)
option(FLATBUFFERS_BUILD_SHAREDLIB
@@ -71,12 +51,35 @@ option(FLATBUFFERS_ENABLE_PCH
Only work if CMake supports 'target_precompile_headers'. \"
This can speed up compilation time."
OFF)
option(FLATBUFFERS_SKIP_MONSTER_EXTRA
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)
option(FLATBUFFERS_STRICT_MODE
"Build flatbuffers with all warnings as errors (-Werror or /WX)."
OFF)
if(NOT DEFINED FLATBUFFERS_CPP_STD)
set(FLATBUFFERS_CPP_STD 11)
endif()
set(MSVC_LIKE OFF)
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})
set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE "time -f 'Wall: %E User: %U Sys: %S | %C' -q -a -o ${FLATBUFFERS_COMPILATION_TIMINGS}")
set_property(GLOBAL PROPERTY RULE_LAUNCH_CUSTOM "time -f 'Wall: %E User: %U Sys: %S | %C' -q -a -o ${FLATBUFFERS_COMPILATION_TIMINGS}")
set_property(GLOBAL PROPERTY RULE_LAUNCH_LINK "time -f 'Wall: %E User: %U Sys: %S | %C' -q -a -o ${FLATBUFFERS_COMPILATION_TIMINGS}")
endif()
if(NOT FLATBUFFERS_BUILD_FLATC AND FLATBUFFERS_BUILD_TESTS)
message(WARNING
@@ -95,7 +98,7 @@ if(NOT DEFINED FLATBUFFERS_LOCALE_INDEPENDENT)
include(CheckCXXSymbolExists)
set(FLATBUFFERS_LOCALE_INDEPENDENT 0)
if(MSVC)
if(MSVC_LIKE)
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()
@@ -108,18 +111,28 @@ if(NOT DEFINED FLATBUFFERS_LOCALE_INDEPENDENT)
endif()
add_definitions(-DFLATBUFFERS_LOCALE_INDEPENDENT=$<BOOL:${FLATBUFFERS_LOCALE_INDEPENDENT}>)
if(NOT WIN32)
include(CheckSymbolExists)
check_symbol_exists(realpath "stdlib.h" HAVE_REALPATH)
if(NOT HAVE_REALPATH)
add_definitions(-DFLATBUFFERS_NO_ABSOLUTE_PATH_RESOLUTION)
endif()
endif()
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
include/flatbuffers/flex_flat_util.h
include/flatbuffers/hash.h
include/flatbuffers/idl.h
include/flatbuffers/minireflect.h
@@ -134,6 +147,8 @@ set(FlatBuffers_Library_SRCS
include/flatbuffers/vector.h
include/flatbuffers/vector_downward.h
include/flatbuffers/verifier.h
src/file_manager.cpp
src/file_name_manager.cpp
src/idl_parser.cpp
src/idl_gen_text.cpp
src/reflection.cpp
@@ -142,28 +157,43 @@ 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
src/idl_gen_kotlin.cpp
src/idl_gen_kotlin_kmp.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/idl_namer.h
src/namer.h
src/flatc.cpp
src/flatc_main.cpp
src/bfbs_gen.h
src/bfbs_gen_lua.h
src/bfbs_gen_nim.h
src/bfbs_namer.h
include/codegen/idl_namer.h
include/codegen/namer.h
include/codegen/python.h
include/codegen/python.cc
include/flatbuffers/code_generators.h
src/binary_annotator.h
src/binary_annotator.cpp
src/annotated_binary_text_gen.h
src/annotated_binary_text_gen.cpp
src/bfbs_gen_lua.cpp
src/bfbs_gen_nim.cpp
src/code_generators.cpp
grpc/src/compiler/schema_interface.h
grpc/src/compiler/cpp_generator.h
@@ -188,32 +218,37 @@ set(FlatHash_SRCS
set(FlatBuffers_Tests_SRCS
${FlatBuffers_Library_SRCS}
src/idl_gen_fbs.cpp
tests/default_vectors_strings_test.cpp
tests/default_vectors_strings_test.h
tests/evolution_test.cpp
tests/flexbuffers_test.cpp
tests/fuzz_test.cpp
tests/json_test.cpp
tests/key_field_test.cpp
tests/monster_test.cpp
tests/optional_scalars_test.cpp
tests/parser_test.cpp
tests/proto_test.cpp
tests/reflection_test.cpp
tests/test.cpp
tests/test_assert.h
tests/test_assert.cpp
tests/test_builder.h
tests/test_builder.cpp
tests/util_test.cpp
tests/vector_table_naked_ptr_test.h
tests/vector_table_naked_ptr_test.cpp
tests/native_type_test_impl.h
tests/native_type_test_impl.cpp
tests/cpp_vec_type_test_impl.h
tests/cpp_vec_type_native_type_test_impl.h
tests/cpp_vec_type_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
)
set(FlatBuffers_Tests_CPP17_SRCS
@@ -221,32 +256,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
@@ -262,103 +285,19 @@ 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
grpc/tests/grpctest_callback_compile.cpp
grpc/tests/grpctest_callback_client_compile.cpp
)
# 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()
# 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()
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)
@@ -366,9 +305,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
@@ -379,13 +316,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)
@@ -397,12 +335,121 @@ endfunction()
include_directories(include)
include_directories(grpc)
# Creates an interface library that stores the configuration settings that each
# target links too. This is a compromise between setting configuration globally
# with add_compile_options() and the more targetted target_compile_options().
# This way each target in this file can share settings and override them if
# needed.
add_library(ProjectConfig INTERFACE)
target_compile_features(ProjectConfig
INTERFACE
cxx_std_${FLATBUFFERS_CPP_STD}
)
# Force the standard to be met.
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# We shouldn't rely on any compiler-extensions to make things work.
set(CMAKE_CXX_EXTENSIONS OFF)
if(MSVC_LIKE)
target_compile_options(ProjectConfig
INTERFACE
/W4
$<$<BOOL:${FLATBUFFERS_STRICT_MODE}>:
/WX # Treat all compiler warnings as errors
>
/wd4512 # C4512: assignment operator could not be generated
/wd4316 # C4316: object allocated on the heap may not be aligned
/wd4456 # C4456: hides previous local declaration
$<$<CXX_COMPILER_ID:Clang>:
/D_CRT_SECURE_NO_WARNINGS
>
)
else()
target_compile_options(ProjectConfig
INTERFACE
-Wall
$<$<BOOL:${FLATBUFFERS_STRICT_MODE}>:
-Werror # Treat all compiler warnings as errors
-fno-rtti # Disable runtime type information
$<$<CXX_COMPILER_ID:GNU>:
# False positive string overflow
# https://github.com/google/flatbuffers/issues/7366
-Wno-error=stringop-overflow
>
>
-pedantic
-Wextra
-Wno-unused-parameter
-Wold-style-cast
-fsigned-char
-Wnon-virtual-dtor
# This isn't working for some reason: $<$<CXX_COMPILER_ID:CLANG>:
$<$<BOOL:${IS_CLANG}>:
-Wnewline-eof
-Wno-unknown-warning-option
-Wmissing-declarations
-Wzero-as-null-pointer-constant
$<$<VERSION_GREATER:$<CXX_COMPILER_VERSION>,3.8>:
-Wimplicit-fallthrough
-Wextra-semi
$<$<BOOL:${FLATBUFFERS_STRICT_MODE}>:
-Werror=unused-private-field
>
>
>
$<$<CXX_COMPILER_ID:GNU>:
$<$<VERSION_GREATER:$<CXX_COMPILER_VERSION>,4.4>:
-Wunused-result
-Wunused-parameter
-Werror=unused-parameter
-Wmissing-declarations
>
$<$<VERSION_GREATER:$<CXX_COMPILER_VERSION>,4.7>:
-Wzero-as-null-pointer-constant
>
$<$<VERSION_GREATER:$<CXX_COMPILER_VERSION>,7.0>:
-faligned-new
$<$<BOOL:${FLATBUFFERS_STRICT_MODE}>:
-Werror=implicit-fallthrough=2
>
>
$<$<VERSION_GREATER:$<CXX_COMPILER_VERSION>,8.0>:
-Wextra-semi
>
>
$<$<BOOL:${FLATBUFFERS_CODE_COVERAGE}>:
-g
-fprofile-arcs
-ftest-coverage
>
)
if(FLATBUFFERS_CODE_COVERAGE)
target_link_options(ProjectConfig
INTERFACE
-fprofile-arcs
-ftest-coverage
)
endif()
endif()
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}")
target_include_directories(flatbuffers
INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
)
target_link_libraries(flatbuffers PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
if(FLATBUFFERS_ENABLE_PCH)
add_pch_to_target(flatbuffers include/flatbuffers/pch/pch.h)
endif()
@@ -413,17 +460,21 @@ if(FLATBUFFERS_BUILD_FLATC)
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}")
target_link_libraries(flatc PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
target_compile_options(flatc
PRIVATE
$<$<AND:$<BOOL:${MSVC_LIKE}>,$<CONFIG:Release>>:
/MT
>
)
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()
@@ -431,184 +482,120 @@ endif()
if(FLATBUFFERS_BUILD_FLATHASH)
add_executable(flathash ${FlatHash_SRCS})
target_link_libraries(flathash PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
endif()
if(FLATBUFFERS_BUILD_SHAREDLIB)
add_library(flatbuffers_shared SHARED ${FlatBuffers_Library_SRCS})
# Shared object version: "major.minor.micro"
# - micro updated every release when there is no API/ABI changes
# - minor updated when there are additions in API/ABI
# - major (ABI number) updated when there are changes in ABI (or removals)
set(FlatBuffers_Library_SONAME_MAJOR ${VERSION_MAJOR})
set(FlatBuffers_Library_SONAME_FULL "${FlatBuffers_Library_SONAME_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}")
set_target_properties(flatbuffers_shared PROPERTIES OUTPUT_NAME flatbuffers
SOVERSION "${FlatBuffers_Library_SONAME_MAJOR}"
target_link_libraries(flatbuffers_shared PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
# 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}'")
function(compile_schema SRC_FBS OPT SUFFIX OUT_GEN_FILE)
get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH)
string(REGEX REPLACE "\\.fbs$" "_generated.h" GEN_HEADER ${SRC_FBS})
string(REGEX REPLACE "\\.fbs$" "${SUFFIX}.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})
${OPT}
--filename-suffix ${SUFFIX}
-o "${SRC_FBS_DIR}"
"${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}"
DEPENDS flatc ${SRC_FBS}
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}" "_generated" 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 ${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})
function(compile_schema_for_test_fbsh SRC_FBS OPT)
compile_schema("${SRC_FBS}" "${OPT}" ".fbs" GEN_FILE)
target_sources(flattests PRIVATE ${GEN_FILE})
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}" "_generated" GEN_FILE)
target_sources(flatsample PRIVATE ${GEN_FILE})
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(Python3 3.5 COMPONENTS Interpreter)
if(Python3_Interpreter_FOUND)
set(GENERATION_OPTS --flatc "${FLATBUFFERS_FLATC_EXECUTABLE}")
if(FLATBUFFERS_BUILD_LEGACY)
# Need to set --cpp-std c++-0x options
set(GENERATION_OPTS ${GENERATION_OPTS}--cpp-0x)
endif()
if(FLATBUFFERS_SKIP_MONSTER_EXTRA)
set(GENERATION_OPTS ${GENERATION_OPTS} --skip-monster-extra)
endif()
add_custom_command(
TARGET flatc
POST_BUILD
COMMAND ${Python3_EXECUTABLE} scripts/generate_code.py ${GENERATION_OPTS} --skip-gen-reflection
WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
COMMENT "Running scripts/generate_code.py..."
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)
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
)
# 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_COMP --cpp --gen-compare --gen-mutable --gen-object-api --reflect-names)
SET(FLATC_OPT_SCOPED_ENUMS ${FLATC_OPT_COMP};--scoped-enums)
compile_schema_for_test(tests/alignment_test.fbs "${FLATC_OPT_COMP}")
compile_schema_for_test_fbsh(tests/default_vectors_strings_test.fbs "${FLATC_OPT_COMP}")
compile_schema_for_test(tests/arrays_test.fbs "${FLATC_OPT_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_COMP}")
compile_schema_for_test(tests/cpp_vec_type_test.fbs "${FLATC_OPT_COMP}")
compile_schema_for_test(tests/cpp_vec_type_native_type_test.fbs "${FLATC_OPT_COMP}")
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_SCOPED_ENUMS}")
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)
# Add a library so there is a single target that the generated samples can
# link too.
if(MSVC OR ${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.20.0")
add_library(flatsample INTERFACE)
else()
add_library(flatsample STATIC)
endif()
# Since flatsample has no sources, we have to explicitly set the linker lang.
set_target_properties(flatsample PROPERTIES LINKER_LANGUAGE CXX)
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"
# 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
)
target_link_libraries(flattests_cpp17 PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
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})
endif()
@@ -616,9 +603,6 @@ if(FLATBUFFERS_BUILD_TESTS)
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()
@@ -633,15 +617,16 @@ 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(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()
target_link_libraries(grpctest
PRIVATE
$<BUILD_INTERFACE:ProjectConfig>
gRPC::grpc++_unsecure
gRPC::gpr
pthread
dl
)
endif()
if(FLATBUFFERS_INSTALL)
include(GNUInstallDirs)
@@ -649,21 +634,24 @@ if(FLATBUFFERS_INSTALL)
set(FB_CMAKE_DIR "${CMAKE_INSTALL_LIBDIR}/cmake/flatbuffers")
configure_file(CMake/FlatbuffersConfigVersion.cmake.in FlatbuffersConfigVersion.cmake @ONLY)
configure_file(CMake/flatbuffers-config-version.cmake.in flatbuffers-config-version.cmake @ONLY)
install(
FILES "CMake/FlatbuffersConfig.cmake" "${CMAKE_CURRENT_BINARY_DIR}/FlatbuffersConfigVersion.cmake"
FILES
"CMake/flatbuffers-config.cmake"
"CMake/BuildFlatBuffers.cmake"
"${CMAKE_CURRENT_BINARY_DIR}/flatbuffers-config-version.cmake"
DESTINATION ${FB_CMAKE_DIR}
)
if(FLATBUFFERS_BUILD_FLATLIB)
install(
TARGETS flatbuffers EXPORT FlatbuffersTargets
TARGETS flatbuffers EXPORT FlatBuffersTargets
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)
install(EXPORT FlatbuffersTargets
FILE FlatbuffersTargets.cmake
install(EXPORT FlatBuffersTargets
FILE FlatBuffersTargets.cmake
NAMESPACE flatbuffers::
DESTINATION ${FB_CMAKE_DIR}
)
@@ -685,7 +673,7 @@ if(FLATBUFFERS_INSTALL)
if(FLATBUFFERS_BUILD_SHAREDLIB)
install(
TARGETS flatbuffers_shared EXPORT FlatbuffersSharedTargets
TARGETS flatbuffers_shared EXPORT FlatBuffersSharedTargets
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
@@ -693,8 +681,8 @@ if(FLATBUFFERS_INSTALL)
)
install(
EXPORT FlatbuffersSharedTargets
FILE FlatbuffersSharedTargets.cmake
EXPORT FlatBuffersSharedTargets
FILE FlatBuffersSharedTargets.cmake
NAMESPACE flatbuffers::
DESTINATION ${FB_CMAKE_DIR}
)
@@ -721,16 +709,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)
@@ -756,4 +734,4 @@ add_library(FlatBuffers::FlatBuffers ALIAS FlatBuffers)
target_include_directories(
FlatBuffers
INTERFACE $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}/include>)
$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}/include>)

View File

@@ -30,7 +30,7 @@ Some tips for good pull requests:
* Write a descriptive commit message. What problem are you solving and what
are the consequences? Where and what did you test? Some good tips:
[here](http://robots.thoughtbot.com/5-useful-tips-for-a-better-commit-message)
and [here](https://www.kernel.org/doc/Documentation/SubmittingPatches).
and [here](https://www.kernel.org/doc/Documentation/process/submitting-patches.rst).
* If your PR consists of multiple commits which are successive improvements /
fixes to your first commit, consider squashing them into a single commit
(`git rebase -i`) such that your PR is a single commit on top of the current
@@ -40,3 +40,26 @@ Some tips for good pull requests:
# The small print
Contributions made by corporations are covered by a different agreement than
the one above, the Software Grant and Corporate Contributor License Agreement.
# Code
TL/DR
See [how to build flatc](https://flatbuffers.dev/building/).
When making changes, build `flatc` and then re-generate the goldens files to see the effect of your changes:
```
$ cp build/flatc .
$ goldens/generate_goldens.py
```
Re-generate other code files to see the effects of the changes:
```
$ scripts/generate_code.py
```
Run tests with [TestAll.sh](tests/TestAll.sh) in [tests](tests), or directly any of the sub-scripts run by it.
[Format the code](Formatters.md) before submitting a PR.

View File

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

View File

@@ -19,4 +19,4 @@ Swift uses swiftformat as it's formatter. Take a look at [how to install here](h
## Typescript
Typescript uses eslint as it's linter. Take a look at [how to install here](https://eslint.org/docs/user-guide/getting-started). Run the following command `eslint ts/** --ext .ts` in the root directory of the project
Typescript uses eslint as it's linter. Take a look at [how to install here](https://eslint.org/docs/user-guide/getting-started). Run the following command `eslint ts/** --ext .ts` in the root directory of the project

78
MODULE.bazel Normal file
View File

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

80
Package.swift Normal file
View File

@@ -0,0 +1,80 @@
// swift-tools-version:5.10
/*
* Copyright 2020 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import PackageDescription
let package = Package(
name: "FlatBuffers",
platforms: [
.iOS(.v12),
.macOS(.v10_14),
],
products: [
.library(
name: "FlatBuffers",
targets: ["FlatBuffers"]),
.library(
name: "FlexBuffers",
targets: ["FlexBuffers"]),
],
dependencies: .dependencies,
targets: [
.target(
name: "FlatBuffers",
dependencies: ["Common"],
path: "swift/Sources/FlatBuffers"),
.target(
name: "FlexBuffers",
dependencies: ["Common"],
path: "swift/Sources/FlexBuffers"),
.target(
name: "Common",
path: "swift/Sources/Common"),
.testTarget(
name: "FlatbuffersTests",
dependencies: .dependencies,
path: "tests/swift/Tests/Flatbuffers"),
.testTarget(
name: "FlexbuffersTests",
dependencies: ["FlexBuffers"],
path: "tests/swift/Tests/Flexbuffers"),
])
extension Array where Element == Package.Dependency {
static var dependencies: [Package.Dependency] {
#if os(Windows)
[]
#else
// Test only Dependency
[.package(url: "https://github.com/grpc/grpc-swift.git", from: "1.4.1")]
#endif
}
}
extension Array where Element == PackageDescription.Target.Dependency {
static var dependencies: [PackageDescription.Target.Dependency] {
#if os(Windows)
["FlatBuffers"]
#else
// Test only Dependency
[
.product(name: "GRPC", package: "grpc-swift"),
"FlatBuffers",
]
#endif
}
}

116
README.md Normal file
View File

@@ -0,0 +1,116 @@
![logo](https://flatbuffers.dev/assets/flatbuffers_logo.svg) FlatBuffers
===========
![Build status](https://github.com/google/flatbuffers/actions/workflows/build.yml/badge.svg?branch=master)
[![BuildKite status](https://badge.buildkite.com/7979d93bc6279aa539971f271253c65d5e8fe2fe43c90bbb25.svg)](https://buildkite.com/bazel/flatbuffers)
[![Fuzzing Status](https://oss-fuzz-build-logs.storage.googleapis.com/badges/flatbuffers.svg)](https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&can=1&q=proj:flatbuffers)
[![Discord Chat](https://img.shields.io/discord/656202785926152206.svg)](https:///discord.gg/6qgKs3R)
[![Twitter Follow](https://img.shields.io/twitter/follow/wvo.svg?style=social)](https://twitter.com/wvo)
[![Twitter Follow](https://img.shields.io/twitter/follow/dbaileychess.svg?style=social)](https://twitter.com/dbaileychess)
**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 compilation (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)
## Supported programming languages
Code generation and runtime libraries for many popular languages.
1. C
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)
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. 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)
1. Nim
## 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.
## Contribution
* [FlatBuffers Issues Tracker][] to submit an issue.
* [stackoverflow.com][] with [`flatbuffers` tag][] for any questions regarding FlatBuffers.
*To contribute to this project,* see [CONTRIBUTING][].
## Community
* [Discord Server](https:///discord.gg/6qgKs3R)
## Security
Please see our [Security Policy](SECURITY.md) for reporting vulnerabilities.
## Licensing
*Flatbuffers* is licensed under the Apache License, Version 2.0. See [LICENSE][] for the full license text.
<br>
[CONTRIBUTING]: http://github.com/google/flatbuffers/blob/master/CONTRIBUTING.md
[`flatbuffers` tag]: https://stackoverflow.com/questions/tagged/flatbuffers
[FlatBuffers Google Group]: https://groups.google.com/forum/#!forum/flatbuffers
[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

View File

@@ -1,46 +0,0 @@
workspace(name = "com_github_google_flatbuffers")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "io_bazel_rules_go",
sha256 = "d1ffd055969c8f8d431e2d439813e42326961d0942bdf734d2c95dc30c369566",
urls = [
"https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.24.5/rules_go-v0.24.5.tar.gz",
"https://github.com/bazelbuild/rules_go/releases/download/v0.24.5/rules_go-v0.24.5.tar.gz",
],
)
load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies")
go_rules_dependencies()
go_register_toolchains()
##### Protobuf
_PROTOBUF_VERSION = "3.15.2"
http_archive(
name = "com_google_protobuf",
strip_prefix = "protobuf-" + _PROTOBUF_VERSION,
urls = [
"https://github.com/protocolbuffers/protobuf/archive/v" + _PROTOBUF_VERSION + ".tar.gz",
],
)
##### GRPC
_GRPC_VERSION = "1.42.0"
http_archive(
name = "com_github_grpc_grpc",
strip_prefix = "grpc-" + _GRPC_VERSION,
urls = ["https://github.com/grpc/grpc/archive/v" + _GRPC_VERSION + ".tar.gz"],
)
load("@com_github_grpc_grpc//bazel:grpc_deps.bzl", "grpc_deps")
grpc_deps()
load("@com_github_grpc_grpc//bazel:grpc_extra_deps.bzl", "grpc_extra_deps")
grpc_extra_deps()

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>1672434305228</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

@@ -3,10 +3,12 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.FlatBufferTest">
<uses-sdk android:minSdkVersion="14"/>
<uses-feature android:glEsVersion="0x00020000"></uses-feature>
<!-- This .apk has no Java code itself, so set hasCode to false. -->
<application android:label="@string/app_name"
<application android:name="android.support.multidex.MultiDexApplication"
android:label="@string/app_name"
android:hasCode="false"
android:allowBackup="false">
<!-- Our activity is the built-in NativeActivity framework class.

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 16
targetSdkVersion 30
minSdkVersion 26
targetSdkVersion 33
versionCode 1
versionName "1.0"
@@ -18,6 +16,18 @@ android {
targetCompatibility JavaVersion.VERSION_1_8
}
sourceSets {
main {
java {
srcDir '../../java/src/main/java/'
}
}
}
ndk {
abiFilters 'arm64-v8a', 'armeabi-v7a'
}
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
externalNativeBuild {
cmake {
@@ -33,7 +43,6 @@ android {
}
}
ndkVersion "21.3.6528147"
externalNativeBuild {
cmake {
path "src/main/cpp/CMakeLists.txt"
@@ -52,16 +61,17 @@ android {
fbsFiles.forEach{
commandLineArgs.add(it.path)
}
commandLine commandLineArgs
doFirst {
delete "$outputCppDir/"
mkdir "$outputCppDir/"
}
doLast {
if (execResult.getExitValue() != 0) {
println(standardOutput.toString())
throw new GradleException("flatc command line failed")
if (executionResult.get().exitValue != 0) {
throw new GradleException("flatc failed with: ${executionResult.get().toString()}")
}
}
}
@@ -74,6 +84,10 @@ android {
standardOutput = new ByteArrayOutputStream()
errorOutput = new ByteArrayOutputStream()
setErrorOutput(errorOutput)
setStandardOutput(standardOutput)
def commandLineArgs = ['flatc', '-o', outputKotlinDir, '--kotlin']
fbsFiles.forEach{
commandLineArgs.add(it.path)
@@ -85,50 +99,27 @@ android {
mkdir "$outputKotlinDir/"
}
doLast {
if (execResult.getExitValue() != 0) {
println(standardOutput.toString())
throw new GradleException("flatc command line failed")
if (executionResult.get().exitValue != 0) {
throw new GradleException("flatc failed with: ${executionResult.get().toString()}")
}
}
}
afterEvaluate {
android.applicationVariants.all { variant ->
variant.javaCompiler.dependsOn(generateFbsKotlin)
variant.javaCompiler.dependsOn(generateFbsCpp)
}
}
flavorDimensions "stl-variant"
productFlavors {
gnustl {
dimension "stl-variant"
applicationIdSuffix ".gnustl"
versionNameSuffix "-gnustl"
externalNativeBuild {
ndkBuild {
arguments "APP_STL=gnustl_static"
}
}
}
libcpp {
dimension "stl-variant"
applicationIdSuffix ".libcpp"
versionNameSuffix "-libcpp"
externalNativeBuild {
ndkBuild {
arguments "APP_STL=c++_static"
}
}
tasks.named("preBuild") {
dependsOn(generateFbsKotlin)
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 'com.google.flatbuffers:flatbuffers-java:2.0.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,21 +0,0 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

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

@@ -15,25 +15,27 @@
*/
#include <jni.h>
#include <string>
#include <search.h>
#include <string>
#include "generated/animal_generated.h"
using namespace com::fbs::app;
using namespace flatbuffers;
extern "C" JNIEXPORT jbyteArray JNICALL Java_com_flatbuffers_app_MainActivity_createAnimalFromJNI(
JNIEnv* env,
jobject /* this */) {
// create a new animal flatbuffers
auto fb = FlatBufferBuilder(1024);
auto tiger = CreateAnimalDirect(fb, "Tiger", "Roar", 300);
fb.Finish(tiger);
extern "C" JNIEXPORT jbyteArray JNICALL
Java_com_flatbuffers_app_MainActivity_createAnimalFromJNI(JNIEnv* env,
jobject /* this */) {
// create a new animal flatbuffers
auto fb = FlatBufferBuilder(1024);
auto tiger = CreateAnimalDirect(fb, "Tiger", "Roar", 300);
fb.Finish(tiger);
// copies it to a Java byte array.
auto buf = reinterpret_cast<jbyte*>(fb.GetBufferPointer());
int size = fb.GetSize();
auto ret = env->NewByteArray(size);
env->SetByteArrayRegion (ret, 0, fb.GetSize(), buf);
// copies it to a Java byte array.
auto buf = reinterpret_cast<jbyte*>(fb.GetBufferPointer());
int size = fb.GetSize();
auto ret = env->NewByteArray(size);
env->SetByteArrayRegion(ret, 0, fb.GetSize(), buf);
return ret;
}

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
@@ -26,6 +25,7 @@ set(FlatBuffers_Library_SRCS
${FLATBUFFERS_SRC}/include/flatbuffers/flatbuffer_builder.h
${FLATBUFFERS_SRC}/include/flatbuffers/flatbuffers.h
${FLATBUFFERS_SRC}/include/flatbuffers/flexbuffers.h
${FLATBUFFERS_SRC}/include/flatbuffers/flex_flat_util.h
${FLATBUFFERS_SRC}/include/flatbuffers/hash.h
${FLATBUFFERS_SRC}/include/flatbuffers/idl.h
${FLATBUFFERS_SRC}/include/flatbuffers/minireflect.h
@@ -48,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

@@ -1,11 +1,17 @@
// automatically generated by the FlatBuffers compiler, do not modify
#ifndef FLATBUFFERS_GENERATED_ANIMAL_COM_FBS_APP_H_
#define FLATBUFFERS_GENERATED_ANIMAL_COM_FBS_APP_H_
#include "flatbuffers/flatbuffers.h"
// Ensure the included flatbuffers.h is the same version as when this file was
// generated, otherwise it may not be compatible.
static_assert(FLATBUFFERS_VERSION_MAJOR == 24 &&
FLATBUFFERS_VERSION_MINOR == 12 &&
FLATBUFFERS_VERSION_REVISION == 23,
"Non-compatible flatbuffers version included");
namespace com {
namespace fbs {
namespace app {
@@ -13,62 +19,55 @@ 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 {
return VerifyTableStart(verifier) &&
VerifyOffset(verifier, VT_NAME) &&
verifier.VerifyString(name()) &&
VerifyOffset(verifier, VT_SOUND) &&
uint16_t weight() const { return GetField<uint16_t>(VT_WEIGHT, 0); }
bool Verify(::flatbuffers::Verifier& verifier) const {
return VerifyTableStart(verifier) && VerifyOffset(verifier, VT_NAME) &&
verifier.VerifyString(name()) && VerifyOffset(verifier, VT_SOUND) &&
verifier.VerifyString(sound()) &&
VerifyField<uint16_t>(verifier, VT_WEIGHT) &&
verifier.EndTable();
VerifyField<uint16_t>(verifier, VT_WEIGHT, 2) && verifier.EndTable();
}
};
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)
: fbb_(_fbb) {
explicit AnimalBuilder(::flatbuffers::FlatBufferBuilder& _fbb) : fbb_(_fbb) {
start_ = fbb_.StartTable();
}
AnimalBuilder &operator=(const AnimalBuilder &);
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);
@@ -77,47 +76,39 @@ inline flatbuffers::Offset<Animal> CreateAnimal(
return builder_.Finish();
}
inline flatbuffers::Offset<Animal> CreateAnimalDirect(
flatbuffers::FlatBufferBuilder &_fbb,
const char *name = nullptr,
const char *sound = nullptr,
uint16_t weight = 0) {
inline ::flatbuffers::Offset<Animal> CreateAnimalDirect(
::flatbuffers::FlatBufferBuilder& _fbb, const char* name = nullptr,
const char* sound = nullptr, uint16_t weight = 0) {
auto name__ = name ? _fbb.CreateString(name) : 0;
auto sound__ = sound ? _fbb.CreateString(sound) : 0;
return com::fbs::app::CreateAnimal(
_fbb,
name__,
sound__,
weight);
return com::fbs::app::CreateAnimal(_fbb, name__, sound__, weight);
}
inline const com::fbs::app::Animal *GetAnimal(const void *buf) {
return flatbuffers::GetRoot<com::fbs::app::Animal>(buf);
inline const com::fbs::app::Animal* GetAnimal(const void* 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);
inline const com::fbs::app::Animal* GetSizePrefixedAnimal(const void* buf) {
return ::flatbuffers::GetSizePrefixedRoot<com::fbs::app::Animal>(buf);
}
inline bool VerifyAnimalBuffer(
flatbuffers::Verifier &verifier) {
inline bool VerifyAnimalBuffer(::flatbuffers::Verifier& verifier) {
return verifier.VerifyBuffer<com::fbs::app::Animal>(nullptr);
}
inline bool VerifySizePrefixedAnimalBuffer(
flatbuffers::Verifier &verifier) {
inline bool VerifySizePrefixedAnimalBuffer(::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

@@ -1,9 +1,9 @@
package com.flatbuffers.app
import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.fbs.app.Animal
import com.google.flatbuffers.FlatBufferBuilder
import java.nio.ByteBuffer
@@ -27,14 +27,15 @@ class MainActivity : AppCompatActivity() {
private external fun createAnimalFromJNI(): ByteArray
// Create a "Cow" Animal flatbuffers from Kotlin
private fun createAnimalFromKotlin():Animal {
private fun createAnimalFromKotlin(): Animal {
val fb = FlatBufferBuilder(100)
val cowOffset = Animal.createAnimal(
builder = fb,
nameOffset = fb.createString("Cow"),
soundOffset = fb.createString("Moo"),
weight = 720u
)
val cowOffset =
Animal.createAnimal(
builder = fb,
nameOffset = fb.createString("Cow"),
soundOffset = fb.createString("Moo"),
weight = 720u,
)
fb.finish(cowOffset)
return Animal.getRootAsAnimal(fb.dataBuffer())
}

View File

@@ -2,63 +2,101 @@
package com.fbs.app
import java.nio.*
import kotlin.math.sign
import com.google.flatbuffers.*
import com.google.flatbuffers.Constants
import com.google.flatbuffers.FlatBufferBuilder
import com.google.flatbuffers.Table
import java.nio.ByteBuffer
import java.nio.ByteOrder
@Suppress("unused")
@ExperimentalUnsignedTypes
@kotlin.ExperimentalUnsignedTypes
class Animal : Table() {
fun __init(_i: Int, _bb: ByteBuffer) {
__reset(_i, _bb)
fun __init(_i: Int, _bb: ByteBuffer) {
__reset(_i, _bb)
}
fun __assign(_i: Int, _bb: ByteBuffer): Animal {
__init(_i, _bb)
return this
}
val name: String?
get() {
val o = __offset(4)
return if (o != 0) {
__string(o + bb_pos)
} else {
null
}
}
fun __assign(_i: Int, _bb: ByteBuffer) : Animal {
__init(_i, _bb)
return this
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
}
}
val name : String?
get() {
val o = __offset(4)
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
}
val soundAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(6, 1)
fun soundInByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 6, 1)
val weight : UShort
get() {
val o = __offset(8)
return if(o != 0) bb.getShort(o + bb_pos).toUShort() else 0u
}
companion object {
fun validateVersion() = Constants.FLATBUFFERS_2_0_0()
fun getRootAsAnimal(_bb: ByteBuffer): Animal = getRootAsAnimal(_bb, Animal())
fun getRootAsAnimal(_bb: ByteBuffer, obj: Animal): Animal {
_bb.order(ByteOrder.LITTLE_ENDIAN)
return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb))
}
fun createAnimal(builder: FlatBufferBuilder, nameOffset: Int, soundOffset: Int, weight: UShort) : Int {
builder.startTable(3)
addSound(builder, soundOffset)
addName(builder, nameOffset)
addWeight(builder, weight)
return endAnimal(builder)
}
fun startAnimal(builder: FlatBufferBuilder) = builder.startTable(3)
fun addName(builder: FlatBufferBuilder, name: Int) = builder.addOffset(0, name, 0)
fun addSound(builder: FlatBufferBuilder, sound: Int) = builder.addOffset(1, sound, 0)
fun addWeight(builder: FlatBufferBuilder, weight: UShort) = builder.addShort(2, weight.toShort(), 0)
fun endAnimal(builder: FlatBufferBuilder) : Int {
val o = builder.endTable()
return o
}
fun finishAnimalBuffer(builder: FlatBufferBuilder, offset: Int) = builder.finish(offset)
fun finishSizePrefixedAnimalBuffer(builder: FlatBufferBuilder, offset: Int) = builder.finishSizePrefixed(offset)
val soundAsByteBuffer: ByteBuffer
get() = __vector_as_bytebuffer(6, 1)
fun soundInByteBuffer(_bb: ByteBuffer): ByteBuffer = __vector_in_bytebuffer(_bb, 6, 1)
val weight: UShort
get() {
val o = __offset(8)
return if (o != 0) bb.getShort(o + bb_pos).toUShort() else 0u
}
companion object {
fun validateVersion() = Constants.FLATBUFFERS_25_12_19()
fun getRootAsAnimal(_bb: ByteBuffer): Animal = getRootAsAnimal(_bb, Animal())
fun getRootAsAnimal(_bb: ByteBuffer, obj: Animal): Animal {
_bb.order(ByteOrder.LITTLE_ENDIAN)
return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb))
}
fun createAnimal(
builder: FlatBufferBuilder,
nameOffset: Int,
soundOffset: Int,
weight: UShort,
): Int {
builder.startTable(3)
addSound(builder, soundOffset)
addName(builder, nameOffset)
addWeight(builder, weight)
return endAnimal(builder)
}
fun startAnimal(builder: FlatBufferBuilder) = builder.startTable(3)
fun addName(builder: FlatBufferBuilder, name: Int) = builder.addOffset(0, name, 0)
fun addSound(builder: FlatBufferBuilder, sound: Int) = builder.addOffset(1, sound, 0)
fun addWeight(builder: FlatBufferBuilder, weight: UShort) =
builder.addShort(2, weight.toShort(), 0)
fun endAnimal(builder: FlatBufferBuilder): Int {
val o = builder.endTable()
return o
}
fun finishAnimalBuffer(builder: FlatBufferBuilder, offset: Int) = builder.finish(offset)
fun finishSizePrefixedAnimalBuffer(builder: FlatBufferBuilder, offset: Int) =
builder.finishSizePrefixed(offset)
}
}

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

@@ -19,3 +19,5 @@ android.useAndroidX=true
android.enableJetifier=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
# Use parallel builds
org.gradle.parallel=true

Binary file not shown.

View File

@@ -1,6 +1,5 @@
#Thu Oct 29 19:47:23 CET 2020
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-all.zip

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)
@@ -16,7 +17,7 @@ FetchContent_Declare(
FetchContent_Declare(
googlebenchmark
GIT_REPOSITORY https://github.com/google/benchmark.git
GIT_TAG f91b6b42b1b9854772a90ae9501464a161707d1e # v1.6.0
GIT_TAG 0d98dba29d66e93259db7daa53a9327df767a415 # v1.6.1
)
# For Windows: Prevent overriding the parent project's compiler/linker
@@ -27,7 +28,7 @@ FetchContent_MakeAvailable(
googlebenchmark
)
set(CPP_BENCH_DIR cpp)
set(CPP_BENCH_DIR ${CMAKE_CURRENT_SOURCE_DIR}/cpp)
set(CPP_FB_BENCH_DIR ${CPP_BENCH_DIR}/flatbuffers)
set(CPP_RAW_BENCH_DIR ${CPP_BENCH_DIR}/raw)
set(CPP_BENCH_FBS ${CPP_FB_BENCH_DIR}/bench.fbs)
@@ -62,8 +63,14 @@ 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
PRIVATE
-fno-aligned-new
-Wno-deprecated-declarations
)
# Set the output directory to the root binary directory
@@ -75,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

@@ -8,12 +8,12 @@ struct Bench {
inline void Add(int64_t value) { sum += value; }
virtual uint8_t *Encode(void *buf, int64_t &len) = 0;
virtual void *Decode(void *buf, int64_t len) = 0;
virtual int64_t Use(void *decoded) = 0;
virtual void Dealloc(void *decoded) = 0;
virtual uint8_t* Encode(void* buf, int64_t& len) = 0;
virtual void* Decode(void* buf, int64_t len) = 0;
virtual int64_t Use(void* decoded) = 0;
virtual void Dealloc(void* decoded) = 0;
int64_t sum = 0;
};
#endif // BENCHMARKS_CPP_BENCH_H_
#endif // BENCHMARKS_CPP_BENCH_H_

View File

@@ -5,8 +5,8 @@
#include "benchmarks/cpp/flatbuffers/fb_bench.h"
#include "benchmarks/cpp/raw/raw_bench.h"
static inline void Encode(benchmark::State &state,
std::unique_ptr<Bench> &bench, uint8_t *buffer) {
static inline void Encode(benchmark::State& state,
std::unique_ptr<Bench>& bench, uint8_t* buffer) {
int64_t length;
for (auto _ : state) {
bench->Encode(buffer, length);
@@ -14,31 +14,33 @@ static inline void Encode(benchmark::State &state,
}
}
static inline void Decode(benchmark::State &state,
std::unique_ptr<Bench> &bench, uint8_t *buffer) {
static inline void Decode(benchmark::State& state,
std::unique_ptr<Bench>& bench, uint8_t* buffer) {
int64_t length;
uint8_t *encoded = bench->Encode(buffer, length);
uint8_t* encoded = bench->Encode(buffer, length);
for (auto _ : state) {
void *decoded = bench->Decode(encoded, length);
void* decoded = bench->Decode(encoded, length);
benchmark::DoNotOptimize(decoded);
}
}
static inline void Use(benchmark::State &state, std::unique_ptr<Bench> &bench,
uint8_t *buffer, int64_t check_sum) {
static inline void Use(benchmark::State& state, std::unique_ptr<Bench>& bench,
uint8_t* buffer, int64_t check_sum) {
int64_t length;
uint8_t *encoded = bench->Encode(buffer, length);
void *decoded = bench->Decode(encoded, length);
uint8_t* encoded = bench->Encode(buffer, length);
void* decoded = bench->Decode(encoded, length);
int64_t sum = 0;
for (auto _ : state) { sum = bench->Use(decoded); }
for (auto _ : state) {
sum = bench->Use(decoded);
}
EXPECT_EQ(sum, check_sum);
}
static void BM_Flatbuffers_Encode(benchmark::State &state) {
static void BM_Flatbuffers_Encode(benchmark::State& state) {
const int64_t kBufferLength = 1024;
uint8_t buffer[kBufferLength];
@@ -48,7 +50,7 @@ static void BM_Flatbuffers_Encode(benchmark::State &state) {
}
BENCHMARK(BM_Flatbuffers_Encode);
static void BM_Flatbuffers_Decode(benchmark::State &state) {
static void BM_Flatbuffers_Decode(benchmark::State& state) {
const int64_t kBufferLength = 1024;
uint8_t buffer[kBufferLength];
@@ -58,7 +60,7 @@ static void BM_Flatbuffers_Decode(benchmark::State &state) {
}
BENCHMARK(BM_Flatbuffers_Decode);
static void BM_Flatbuffers_Use(benchmark::State &state) {
static void BM_Flatbuffers_Use(benchmark::State& state) {
const int64_t kBufferLength = 1024;
uint8_t buffer[kBufferLength];
@@ -68,7 +70,7 @@ static void BM_Flatbuffers_Use(benchmark::State &state) {
}
BENCHMARK(BM_Flatbuffers_Use);
static void BM_Raw_Encode(benchmark::State &state) {
static void BM_Raw_Encode(benchmark::State& state) {
const int64_t kBufferLength = 1024;
uint8_t buffer[kBufferLength];
@@ -77,7 +79,7 @@ static void BM_Raw_Encode(benchmark::State &state) {
}
BENCHMARK(BM_Raw_Encode);
static void BM_Raw_Decode(benchmark::State &state) {
static void BM_Raw_Decode(benchmark::State& state) {
const int64_t kBufferLength = 1024;
uint8_t buffer[kBufferLength];
@@ -86,7 +88,7 @@ static void BM_Raw_Decode(benchmark::State &state) {
}
BENCHMARK(BM_Raw_Decode);
static void BM_Raw_Use(benchmark::State &state) {
static void BM_Raw_Use(benchmark::State& state) {
const int64_t kBufferLength = 1024;
uint8_t buffer[kBufferLength];

View File

@@ -1,11 +1,17 @@
// automatically generated by the FlatBuffers compiler, do not modify
#ifndef FLATBUFFERS_GENERATED_BENCH_BENCHMARKS_FLATBUFFERS_H_
#define FLATBUFFERS_GENERATED_BENCH_BENCHMARKS_FLATBUFFERS_H_
#include "flatbuffers/flatbuffers.h"
// Ensure the included flatbuffers.h is the same version as when this file was
// generated, otherwise it may not be compatible.
static_assert(FLATBUFFERS_VERSION_MAJOR == 24 &&
FLATBUFFERS_VERSION_MINOR == 12 &&
FLATBUFFERS_VERSION_REVISION == 23,
"Non-compatible flatbuffers version included");
namespace benchmarks_flatbuffers {
struct Foo;
@@ -27,25 +33,16 @@ enum Enum : int16_t {
};
inline const Enum (&EnumValuesEnum())[3] {
static const Enum values[] = {
Enum_Apples,
Enum_Pears,
Enum_Bananas
};
static const Enum values[] = {Enum_Apples, Enum_Pears, Enum_Bananas};
return values;
}
inline const char * const *EnumNamesEnum() {
static const char * const names[4] = {
"Apples",
"Pears",
"Bananas",
nullptr
};
inline const char* const* EnumNamesEnum() {
static const char* const names[4] = {"Apples", "Pears", "Bananas", nullptr};
return names;
}
inline const char *EnumNameEnum(Enum e) {
inline const char* EnumNameEnum(Enum e) {
if (flatbuffers::IsOutRange(e, Enum_Apples, Enum_Bananas)) return "";
const size_t index = static_cast<size_t>(e);
return EnumNamesEnum()[index];
@@ -60,12 +57,7 @@ FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Foo FLATBUFFERS_FINAL_CLASS {
uint32_t length_;
public:
Foo()
: id_(0),
count_(0),
prefix_(0),
padding0__(0),
length_(0) {
Foo() : id_(0), count_(0), prefix_(0), padding0__(0), length_(0) {
(void)padding0__;
}
Foo(uint64_t _id, int16_t _count, int8_t _prefix, uint32_t _length)
@@ -76,18 +68,10 @@ FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Foo FLATBUFFERS_FINAL_CLASS {
length_(flatbuffers::EndianScalar(_length)) {
(void)padding0__;
}
uint64_t id() const {
return flatbuffers::EndianScalar(id_);
}
int16_t count() const {
return flatbuffers::EndianScalar(count_);
}
int8_t prefix() const {
return flatbuffers::EndianScalar(prefix_);
}
uint32_t length() const {
return flatbuffers::EndianScalar(length_);
}
uint64_t id() const { return flatbuffers::EndianScalar(id_); }
int16_t count() const { return flatbuffers::EndianScalar(count_); }
int8_t prefix() const { return flatbuffers::EndianScalar(prefix_); }
uint32_t length() const { return flatbuffers::EndianScalar(length_); }
};
FLATBUFFERS_STRUCT_END(Foo, 16);
@@ -97,20 +81,17 @@ FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Bar FLATBUFFERS_FINAL_CLASS {
int32_t time_;
float ratio_;
uint16_t size_;
int16_t padding0__; int32_t padding1__;
int16_t padding0__;
int32_t padding1__;
public:
Bar()
: parent_(),
time_(0),
ratio_(0),
size_(0),
padding0__(0),
padding1__(0) {
: parent_(), time_(0), ratio_(0), size_(0), padding0__(0), padding1__(0) {
(void)padding0__;
(void)padding1__;
}
Bar(const benchmarks_flatbuffers::Foo &_parent, int32_t _time, float _ratio, uint16_t _size)
Bar(const benchmarks_flatbuffers::Foo& _parent, int32_t _time, float _ratio,
uint16_t _size)
: parent_(_parent),
time_(flatbuffers::EndianScalar(_time)),
ratio_(flatbuffers::EndianScalar(_ratio)),
@@ -120,18 +101,10 @@ FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Bar FLATBUFFERS_FINAL_CLASS {
(void)padding0__;
(void)padding1__;
}
const benchmarks_flatbuffers::Foo &parent() const {
return parent_;
}
int32_t time() const {
return flatbuffers::EndianScalar(time_);
}
float ratio() const {
return flatbuffers::EndianScalar(ratio_);
}
uint16_t size() const {
return flatbuffers::EndianScalar(size_);
}
const benchmarks_flatbuffers::Foo& parent() const { return parent_; }
int32_t time() const { return flatbuffers::EndianScalar(time_); }
float ratio() const { return flatbuffers::EndianScalar(ratio_); }
uint16_t size() const { return flatbuffers::EndianScalar(size_); }
};
FLATBUFFERS_STRUCT_END(Bar, 32);
@@ -143,34 +116,28 @@ struct FooBar FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
VT_RATING = 8,
VT_POSTFIX = 10
};
const benchmarks_flatbuffers::Bar *sibling() const {
return GetStruct<const benchmarks_flatbuffers::Bar *>(VT_SIBLING);
const benchmarks_flatbuffers::Bar* sibling() const {
return GetStruct<const benchmarks_flatbuffers::Bar*>(VT_SIBLING);
}
const flatbuffers::String *name() const {
return GetPointer<const flatbuffers::String *>(VT_NAME);
const flatbuffers::String* name() const {
return GetPointer<const flatbuffers::String*>(VT_NAME);
}
double rating() const {
return GetField<double>(VT_RATING, 0.0);
}
uint8_t postfix() const {
return GetField<uint8_t>(VT_POSTFIX, 0);
}
bool Verify(flatbuffers::Verifier &verifier) const {
double rating() const { return GetField<double>(VT_RATING, 0.0); }
uint8_t postfix() const { return GetField<uint8_t>(VT_POSTFIX, 0); }
bool Verify(flatbuffers::Verifier& verifier) const {
return VerifyTableStart(verifier) &&
VerifyField<benchmarks_flatbuffers::Bar>(verifier, VT_SIBLING) &&
VerifyOffset(verifier, VT_NAME) &&
verifier.VerifyString(name()) &&
VerifyField<double>(verifier, VT_RATING) &&
VerifyField<uint8_t>(verifier, VT_POSTFIX) &&
verifier.EndTable();
VerifyField<benchmarks_flatbuffers::Bar>(verifier, VT_SIBLING, 8) &&
VerifyOffset(verifier, VT_NAME) && verifier.VerifyString(name()) &&
VerifyField<double>(verifier, VT_RATING, 8) &&
VerifyField<uint8_t>(verifier, VT_POSTFIX, 1) && verifier.EndTable();
}
};
struct FooBarBuilder {
typedef FooBar Table;
flatbuffers::FlatBufferBuilder &fbb_;
flatbuffers::FlatBufferBuilder& fbb_;
flatbuffers::uoffset_t start_;
void add_sibling(const benchmarks_flatbuffers::Bar *sibling) {
void add_sibling(const benchmarks_flatbuffers::Bar* sibling) {
fbb_.AddStruct(FooBar::VT_SIBLING, sibling);
}
void add_name(flatbuffers::Offset<flatbuffers::String> name) {
@@ -182,8 +149,7 @@ struct FooBarBuilder {
void add_postfix(uint8_t postfix) {
fbb_.AddElement<uint8_t>(FooBar::VT_POSTFIX, postfix, 0);
}
explicit FooBarBuilder(flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
explicit FooBarBuilder(flatbuffers::FlatBufferBuilder& _fbb) : fbb_(_fbb) {
start_ = fbb_.StartTable();
}
flatbuffers::Offset<FooBar> Finish() {
@@ -194,10 +160,9 @@ struct FooBarBuilder {
};
inline flatbuffers::Offset<FooBar> CreateFooBar(
flatbuffers::FlatBufferBuilder &_fbb,
const benchmarks_flatbuffers::Bar *sibling = nullptr,
flatbuffers::Offset<flatbuffers::String> name = 0,
double rating = 0.0,
flatbuffers::FlatBufferBuilder& _fbb,
const benchmarks_flatbuffers::Bar* sibling = nullptr,
flatbuffers::Offset<flatbuffers::String> name = 0, double rating = 0.0,
uint8_t postfix = 0) {
FooBarBuilder builder_(_fbb);
builder_.add_rating(rating);
@@ -208,18 +173,12 @@ inline flatbuffers::Offset<FooBar> CreateFooBar(
}
inline flatbuffers::Offset<FooBar> CreateFooBarDirect(
flatbuffers::FlatBufferBuilder &_fbb,
const benchmarks_flatbuffers::Bar *sibling = nullptr,
const char *name = nullptr,
double rating = 0.0,
uint8_t postfix = 0) {
flatbuffers::FlatBufferBuilder& _fbb,
const benchmarks_flatbuffers::Bar* sibling = nullptr,
const char* name = nullptr, double rating = 0.0, uint8_t postfix = 0) {
auto name__ = name ? _fbb.CreateString(name) : 0;
return benchmarks_flatbuffers::CreateFooBar(
_fbb,
sibling,
name__,
rating,
postfix);
return benchmarks_flatbuffers::CreateFooBar(_fbb, sibling, name__, rating,
postfix);
}
struct FooBarContainer FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
@@ -230,49 +189,53 @@ struct FooBarContainer FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
VT_FRUIT = 8,
VT_LOCATION = 10
};
const flatbuffers::Vector<flatbuffers::Offset<benchmarks_flatbuffers::FooBar>> *list() const {
return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<benchmarks_flatbuffers::FooBar>> *>(VT_LIST);
}
bool initialized() const {
return GetField<uint8_t>(VT_INITIALIZED, 0) != 0;
const flatbuffers::Vector<
flatbuffers::Offset<benchmarks_flatbuffers::FooBar>>*
list() const {
return GetPointer<const flatbuffers::Vector<
flatbuffers::Offset<benchmarks_flatbuffers::FooBar>>*>(VT_LIST);
}
bool initialized() const { return GetField<uint8_t>(VT_INITIALIZED, 0) != 0; }
benchmarks_flatbuffers::Enum fruit() const {
return static_cast<benchmarks_flatbuffers::Enum>(GetField<int16_t>(VT_FRUIT, 0));
return static_cast<benchmarks_flatbuffers::Enum>(
GetField<int16_t>(VT_FRUIT, 0));
}
const flatbuffers::String *location() const {
return GetPointer<const flatbuffers::String *>(VT_LOCATION);
const flatbuffers::String* location() const {
return GetPointer<const flatbuffers::String*>(VT_LOCATION);
}
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyOffset(verifier, VT_LIST) &&
bool Verify(flatbuffers::Verifier& verifier) const {
return VerifyTableStart(verifier) && VerifyOffset(verifier, VT_LIST) &&
verifier.VerifyVector(list()) &&
verifier.VerifyVectorOfTables(list()) &&
VerifyField<uint8_t>(verifier, VT_INITIALIZED) &&
VerifyField<int16_t>(verifier, VT_FRUIT) &&
VerifyField<uint8_t>(verifier, VT_INITIALIZED, 1) &&
VerifyField<int16_t>(verifier, VT_FRUIT, 2) &&
VerifyOffset(verifier, VT_LOCATION) &&
verifier.VerifyString(location()) &&
verifier.EndTable();
verifier.VerifyString(location()) && verifier.EndTable();
}
};
struct FooBarContainerBuilder {
typedef FooBarContainer Table;
flatbuffers::FlatBufferBuilder &fbb_;
flatbuffers::FlatBufferBuilder& fbb_;
flatbuffers::uoffset_t start_;
void add_list(flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<benchmarks_flatbuffers::FooBar>>> list) {
void add_list(flatbuffers::Offset<flatbuffers::Vector<
flatbuffers::Offset<benchmarks_flatbuffers::FooBar>>>
list) {
fbb_.AddOffset(FooBarContainer::VT_LIST, list);
}
void add_initialized(bool initialized) {
fbb_.AddElement<uint8_t>(FooBarContainer::VT_INITIALIZED, static_cast<uint8_t>(initialized), 0);
fbb_.AddElement<uint8_t>(FooBarContainer::VT_INITIALIZED,
static_cast<uint8_t>(initialized), 0);
}
void add_fruit(benchmarks_flatbuffers::Enum fruit) {
fbb_.AddElement<int16_t>(FooBarContainer::VT_FRUIT, static_cast<int16_t>(fruit), 0);
fbb_.AddElement<int16_t>(FooBarContainer::VT_FRUIT,
static_cast<int16_t>(fruit), 0);
}
void add_location(flatbuffers::Offset<flatbuffers::String> location) {
fbb_.AddOffset(FooBarContainer::VT_LOCATION, location);
}
explicit FooBarContainerBuilder(flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
explicit FooBarContainerBuilder(flatbuffers::FlatBufferBuilder& _fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
}
flatbuffers::Offset<FooBarContainer> Finish() {
@@ -283,8 +246,10 @@ struct FooBarContainerBuilder {
};
inline flatbuffers::Offset<FooBarContainer> CreateFooBarContainer(
flatbuffers::FlatBufferBuilder &_fbb,
flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<benchmarks_flatbuffers::FooBar>>> list = 0,
flatbuffers::FlatBufferBuilder& _fbb,
flatbuffers::Offset<flatbuffers::Vector<
flatbuffers::Offset<benchmarks_flatbuffers::FooBar>>>
list = 0,
bool initialized = false,
benchmarks_flatbuffers::Enum fruit = benchmarks_flatbuffers::Enum_Apples,
flatbuffers::Offset<flatbuffers::String> location = 0) {
@@ -297,47 +262,52 @@ inline flatbuffers::Offset<FooBarContainer> CreateFooBarContainer(
}
inline flatbuffers::Offset<FooBarContainer> CreateFooBarContainerDirect(
flatbuffers::FlatBufferBuilder &_fbb,
const std::vector<flatbuffers::Offset<benchmarks_flatbuffers::FooBar>> *list = nullptr,
flatbuffers::FlatBufferBuilder& _fbb,
const std::vector<flatbuffers::Offset<benchmarks_flatbuffers::FooBar>>*
list = nullptr,
bool initialized = false,
benchmarks_flatbuffers::Enum fruit = benchmarks_flatbuffers::Enum_Apples,
const char *location = nullptr) {
auto list__ = list ? _fbb.CreateVector<flatbuffers::Offset<benchmarks_flatbuffers::FooBar>>(*list) : 0;
const char* location = nullptr) {
auto list__ =
list ? _fbb.CreateVector<
flatbuffers::Offset<benchmarks_flatbuffers::FooBar>>(*list)
: 0;
auto location__ = location ? _fbb.CreateString(location) : 0;
return benchmarks_flatbuffers::CreateFooBarContainer(
_fbb,
list__,
initialized,
fruit,
location__);
_fbb, list__, initialized, fruit, location__);
}
inline const benchmarks_flatbuffers::FooBarContainer *GetFooBarContainer(const void *buf) {
inline const benchmarks_flatbuffers::FooBarContainer* GetFooBarContainer(
const void* buf) {
return flatbuffers::GetRoot<benchmarks_flatbuffers::FooBarContainer>(buf);
}
inline const benchmarks_flatbuffers::FooBarContainer *GetSizePrefixedFooBarContainer(const void *buf) {
return flatbuffers::GetSizePrefixedRoot<benchmarks_flatbuffers::FooBarContainer>(buf);
inline const benchmarks_flatbuffers::FooBarContainer*
GetSizePrefixedFooBarContainer(const void* buf) {
return flatbuffers::GetSizePrefixedRoot<
benchmarks_flatbuffers::FooBarContainer>(buf);
}
inline bool VerifyFooBarContainerBuffer(
flatbuffers::Verifier &verifier) {
return verifier.VerifyBuffer<benchmarks_flatbuffers::FooBarContainer>(nullptr);
inline bool VerifyFooBarContainerBuffer(flatbuffers::Verifier& verifier) {
return verifier.VerifyBuffer<benchmarks_flatbuffers::FooBarContainer>(
nullptr);
}
inline bool VerifySizePrefixedFooBarContainerBuffer(
flatbuffers::Verifier &verifier) {
return verifier.VerifySizePrefixedBuffer<benchmarks_flatbuffers::FooBarContainer>(nullptr);
flatbuffers::Verifier& verifier) {
return verifier
.VerifySizePrefixedBuffer<benchmarks_flatbuffers::FooBarContainer>(
nullptr);
}
inline void FinishFooBarContainerBuffer(
flatbuffers::FlatBufferBuilder &fbb,
flatbuffers::FlatBufferBuilder& fbb,
flatbuffers::Offset<benchmarks_flatbuffers::FooBarContainer> root) {
fbb.Finish(root);
}
inline void FinishSizePrefixedFooBarContainerBuffer(
flatbuffers::FlatBufferBuilder &fbb,
flatbuffers::FlatBufferBuilder& fbb,
flatbuffers::Offset<benchmarks_flatbuffers::FooBarContainer> root) {
fbb.FinishSizePrefixed(root);
}

View File

@@ -13,10 +13,10 @@ using namespace benchmarks_flatbuffers;
namespace {
struct FlatBufferBench : Bench {
explicit FlatBufferBench(int64_t initial_size, Allocator *allocator)
explicit FlatBufferBench(int64_t initial_size, Allocator* allocator)
: fbb(initial_size, allocator, false) {}
uint8_t *Encode(void *, int64_t &len) {
uint8_t* Encode(void*, int64_t& len) override {
fbb.Clear();
const int kVectorLength = 3;
@@ -40,7 +40,7 @@ struct FlatBufferBench : Bench {
return fbb.GetBufferPointer();
}
int64_t Use(void *decoded) {
int64_t Use(void* decoded) override {
sum = 0;
auto foobarcontainer = GetFooBarContainer(decoded);
sum = 0;
@@ -56,7 +56,7 @@ struct FlatBufferBench : Bench {
Add(static_cast<int64_t>(bar->ratio()));
Add(bar->size());
Add(bar->time());
auto &foo = bar->parent();
auto& foo = bar->parent();
Add(foo.count());
Add(foo.id());
Add(foo.length());
@@ -65,8 +65,8 @@ struct FlatBufferBench : Bench {
return sum;
}
void *Decode(void *buffer, int64_t) { return buffer; }
void Dealloc(void *) override{};
void* Decode(void* buffer, int64_t) override { return buffer; }
void Dealloc(void*) override {};
FlatBufferBuilder fbb;
};
@@ -74,7 +74,7 @@ struct FlatBufferBench : Bench {
} // namespace
std::unique_ptr<Bench> NewFlatBuffersBench(int64_t initial_size,
Allocator *allocator) {
Allocator* allocator) {
return std::unique_ptr<FlatBufferBench>(
new FlatBufferBench(initial_size, allocator));
}

View File

@@ -8,16 +8,16 @@
#include "include/flatbuffers/flatbuffers.h"
struct StaticAllocator : public flatbuffers::Allocator {
explicit StaticAllocator(uint8_t *buffer) : buffer_(buffer) {}
explicit StaticAllocator(uint8_t* buffer) : buffer_(buffer) {}
uint8_t *allocate(size_t) override { return buffer_; }
uint8_t* allocate(size_t) override { return buffer_; }
void deallocate(uint8_t *, size_t) override {}
void deallocate(uint8_t*, size_t) override {}
uint8_t *buffer_;
uint8_t* buffer_;
};
std::unique_ptr<Bench> NewFlatBuffersBench(
int64_t initial_size = 1024, flatbuffers::Allocator *allocator = nullptr);
int64_t initial_size = 1024, flatbuffers::Allocator* allocator = nullptr);
#endif // BENCHMARKS_CPP_FLATBUFFERS_FB_BENCH_H_

View File

@@ -45,8 +45,8 @@ struct FooBarContainer {
};
struct RawBench : Bench {
uint8_t *Encode(void *buf, int64_t &len) {
FooBarContainer *fbc = new (buf) FooBarContainer;
uint8_t* Encode(void* buf, int64_t& len) override {
FooBarContainer* fbc = new (buf) FooBarContainer;
strcpy(fbc->location, "http://google.com/flatbuffers/"); // Unsafe eek!
fbc->location_len = (int)strlen(fbc->location);
fbc->fruit = Bananas;
@@ -54,16 +54,16 @@ struct RawBench : Bench {
for (int i = 0; i < kVectorLength; i++) {
// We add + i to not make these identical copies for a more realistic
// compression test.
auto &foobar = fbc->list[i];
auto& foobar = fbc->list[i];
foobar.rating = 3.1415432432445543543 + i;
foobar.postfix = '!' + i;
strcpy(foobar.name, "Hello, World!");
foobar.name_len = (int)strlen(foobar.name);
auto &bar = foobar.sibling;
auto& bar = foobar.sibling;
bar.ratio = 3.14159f + i;
bar.size = 10000 + i;
bar.time = 123456 + i;
auto &foo = bar.parent;
auto& foo = bar.parent;
foo.id = 0xABADCAFEABADCAFE + i;
foo.count = 10000 + i;
foo.length = 1000000 + i;
@@ -71,11 +71,11 @@ struct RawBench : Bench {
}
len = sizeof(FooBarContainer);
return reinterpret_cast<uint8_t *>(fbc);
return reinterpret_cast<uint8_t*>(fbc);
};
int64_t Use(void *decoded) {
auto foobarcontainer = reinterpret_cast<FooBarContainer *>(decoded);
int64_t Use(void* decoded) override {
auto foobarcontainer = reinterpret_cast<FooBarContainer*>(decoded);
sum = 0;
Add(foobarcontainer->initialized);
Add(foobarcontainer->location_len);
@@ -89,7 +89,7 @@ struct RawBench : Bench {
Add(static_cast<int64_t>(bar->ratio));
Add(bar->size);
Add(bar->time);
auto &foo = bar->parent;
auto& foo = bar->parent;
Add(foo.count);
Add(foo.id);
Add(foo.length);
@@ -98,8 +98,8 @@ struct RawBench : Bench {
return sum;
}
void *Decode(void *buf, int64_t) { return buf; }
void Dealloc(void *) override{};
void* Decode(void* buf, int64_t) override { return buf; }
void Dealloc(void*) override {};
};
} // namespace

View File

@@ -0,0 +1,250 @@
/*
* Copyright 2024 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Benchmark
import FlatBuffers
import Foundation
@usableFromInline
struct AA: NativeStruct {
public init(a: Double, b: Double) {
self.a = a
self.b = b
}
var a: Double
var b: Double
}
let benchmarks = {
let oneGB: Int32 = 1_024_000_000
let data = {
var array = [8888.88, 8888.88]
var data = Data()
array.withUnsafeBytes { ptr in
data.append(contentsOf: ptr)
}
return data
}()
let ints: [Int] = Array(repeating: 42, count: 100)
let bytes: [UInt8] = Array(repeating: 42, count: 100)
let str10 = (0...9).map { _ -> String in "x" }.joined()
let str100 = (0...99).map { _ -> String in "x" }.joined()
let array: [AA] = [
AA(a: 2.4, b: 2.4),
AA(a: 2.4, b: 2.4),
AA(a: 2.4, b: 2.4),
AA(a: 2.4, b: 2.4),
AA(a: 2.4, b: 2.4),
]
let metrics: [BenchmarkMetric] = [
.cpuTotal,
.wallClock,
.mallocCountTotal,
.releaseCount,
.peakMemoryResident,
]
let maxIterations = 1_000_000
let maxDuration: Duration = .seconds(3)
let singleConfiguration: Benchmark.Configuration = .init(
metrics: metrics,
warmupIterations: 1,
scalingFactor: .one,
maxDuration: maxDuration,
maxIterations: maxIterations)
let kiloConfiguration: Benchmark.Configuration = .init(
metrics: metrics,
warmupIterations: 1,
scalingFactor: .kilo,
maxDuration: maxDuration,
maxIterations: maxIterations)
let megaConfiguration: Benchmark.Configuration = .init(
metrics: metrics,
warmupIterations: 1,
scalingFactor: .mega,
maxDuration: maxDuration,
maxIterations: maxIterations)
Benchmark.defaultConfiguration = megaConfiguration
Benchmark("Allocating 1GB", configuration: singleConfiguration) { benchmark in
for _ in benchmark.scaledIterations {
blackHole(FlatBufferBuilder(initialSize: oneGB))
}
}
Benchmark(
"Allocating ByteBuffer 1GB",
configuration: singleConfiguration)
{ benchmark in
let memory = UnsafeMutableRawPointer.allocate(
byteCount: 1_024_000_000,
alignment: 1)
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
blackHole(ByteBuffer(assumingMemoryBound: memory, capacity: Int(oneGB)))
}
}
Benchmark("Clearing 1GB", configuration: singleConfiguration) { benchmark in
var fb = FlatBufferBuilder(initialSize: oneGB)
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
blackHole(fb.clear())
}
}
Benchmark("Strings 10") { benchmark in
var fb = FlatBufferBuilder(initialSize: 1 << 20)
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
blackHole(fb.create(string: str10))
}
}
Benchmark("Strings 100") { benchmark in
var fb = FlatBufferBuilder(initialSize: 1 << 20)
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
blackHole(fb.create(string: str100))
}
}
Benchmark("Vector 1 Bytes") { benchmark in
var fb = FlatBufferBuilder(initialSize: 1 << 20)
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
blackHole(fb.createVector(bytes: bytes))
}
}
Benchmark("Vector 1 Ints") { benchmark in
var fb = FlatBufferBuilder(initialSize: 1 << 20)
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
blackHole(fb.createVector(ints))
}
}
Benchmark("Vector 100 Ints") { benchmark in
var fb = FlatBufferBuilder(initialSize: 1 << 20)
benchmark.startMeasurement()
for i in benchmark.scaledIterations {
blackHole(fb.createVector(ints))
}
}
Benchmark("Vector 100 Bytes") { benchmark in
var fb = FlatBufferBuilder(initialSize: 1 << 20)
benchmark.startMeasurement()
for i in benchmark.scaledIterations {
blackHole(fb.createVector(bytes))
}
}
Benchmark("Vector 100 ContiguousBytes") { benchmark in
var fb = FlatBufferBuilder(initialSize: 1 << 20)
benchmark.startMeasurement()
for i in benchmark.scaledIterations {
blackHole(fb.createVector(bytes: bytes))
}
}
Benchmark(
"FlatBufferBuilder Add",
configuration: kiloConfiguration)
{ benchmark in
var fb = FlatBufferBuilder(initialSize: 1024 * 1024 * 32)
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
let off = fb.create(string: "T")
let s = fb.startTable(with: 4)
fb.add(element: 3.2, def: 0, at: 2)
fb.add(element: 4.2, def: 0, at: 4)
fb.add(element: 5.2, def: 0, at: 6)
fb.add(offset: off, at: 8)
blackHole(fb.endTable(at: s))
}
}
Benchmark(
"FlatBufferBuilder Start table",
configuration: kiloConfiguration)
{ benchmark in
var fb = FlatBufferBuilder(initialSize: 1024 * 1024 * 32)
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
let s = fb.startTable(with: 4)
blackHole(fb.endTable(at: s))
}
}
Benchmark("Struct") { benchmark in
var fb = FlatBufferBuilder(initialSize: 1024 * 1024 * 32)
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
blackHole(fb.create(struct: array.first!))
}
}
Benchmark("Structs") { benchmark in
let rawSize = ((16 * 5) * benchmark.scaledIterations.count) / 1024
var fb = FlatBufferBuilder(initialSize: Int32(rawSize * 1600))
var offsets: [Offset] = []
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
let vector = fb.createVector(
ofStructs: array)
let start = fb.startTable(with: 1)
fb.add(offset: vector, at: 4)
offsets.append(Offset(offset: fb.endTable(at: start)))
}
let vector = fb.createVector(ofOffsets: offsets)
let start = fb.startTable(with: 1)
fb.add(offset: vector, at: 4)
let root = Offset(offset: fb.endTable(at: start))
blackHole(fb.finish(offset: root))
}
Benchmark("Vector of Offsets") { benchmark in
let rawSize = ((16 * 5) * benchmark.scaledIterations.count) / 1024
var fb = FlatBufferBuilder(initialSize: Int32(rawSize * 1600))
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
let offsets = [
fb.create(string: "T"),
fb.create(string: "2"),
fb.create(string: "3"),
]
let off = fb.createVector(ofOffsets: [
fb.createVector(ofOffsets: offsets),
fb.createVector(ofOffsets: offsets),
])
let s = fb.startTable(with: 2)
fb.add(offset: off, at: 2)
blackHole(fb.endTable(at: s))
}
}
Benchmark("Reading Doubles") { benchmark in
let byteBuffer = ByteBuffer(data: data)
for _ in benchmark.scaledIterations {
blackHole(byteBuffer.read(def: Double.self, position: 0))
}
}
}

View File

@@ -1,4 +1,4 @@
// swift-tools-version:5.2
// swift-tools-version:5.10
/*
* Copyright 2020 Google Inc. All rights reserved.
*
@@ -18,19 +18,25 @@
import PackageDescription
let package = Package(
name: "FlatBuffers",
name: "benchmarks",
platforms: [
.iOS(.v11),
.macOS(.v10_14),
.macOS(.v13),
],
products: [
.library(
name: "FlatBuffers",
targets: ["FlatBuffers"]),
dependencies: [
.package(path: "../.."),
.package(
url: "https://github.com/ordo-one/package-benchmark",
from: "1.27.0"),
],
targets: [
.target(
name: "FlatBuffers",
dependencies: [],
exclude: ["Documentation.docc/Resources/code/swift"]),
.executableTarget(
name: "FlatbuffersBenchmarks",
dependencies: [
.product(name: "FlatBuffers", package: "flatbuffers"),
.product(name: "Benchmark", package: "package-benchmark"),
],
path: "Benchmarks/FlatbuffersBenchmarks",
plugins: [
.plugin(name: "BenchmarkPlugin", package: "package-benchmark"),
]),
])

View File

@@ -0,0 +1,9 @@
# Benchmarks
To open the benchmarks in xcode use:
`open --env BENCHMARK_DISABLE_JEMALLOC=true Package.swift`
or running them directly within terminal using:
`swift package benchmark`

View File

@@ -7,14 +7,23 @@ Rules for building C++ flatbuffers with Bazel.
load("@rules_cc//cc:defs.bzl", "cc_library")
flatc_path = "@com_github_google_flatbuffers//:flatc"
TRUE_FLATC_PATH = Label("//:flatc")
DEFAULT_INCLUDE_PATHS = [
"./",
"$(GENDIR)",
"$(BINDIR)",
"$(execpath %s).runfiles/%s" % (TRUE_FLATC_PATH, TRUE_FLATC_PATH.repo_name),
]
def default_include_paths(flatc_path):
return [
"./",
"$(GENDIR)",
"$(BINDIR)",
"$(execpath %s).runfiles/%s" % (flatc_path, flatc_path.repo_name),
]
DEFAULT_FLATC_ARGS = [
"--gen-object-api",
"--gen-compare",
@@ -31,13 +40,18 @@ def flatbuffer_library_public(
language_flag,
out_prefix = "",
includes = [],
include_paths = DEFAULT_INCLUDE_PATHS,
include_paths = None,
flatc_args = DEFAULT_FLATC_ARGS,
reflection_name = "",
reflection_visibility = None,
compatible_with = None,
restricted_to = None,
output_to_bindir = False):
target_compatible_with = None,
flatc_path = None,
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:
@@ -58,15 +72,33 @@ def flatbuffer_library_public(
built for, in addition to default-supported environments.
restricted_to: Optional, The list of environments this rule can be built
for, instead of default-supported environments.
target_compatible_with: Optional, The list of target platform constraints
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
optionally a Fileset([reflection_name]) with all generated reflection
binaries.
"""
if flatc_path == None:
flatc_path = TRUE_FLATC_PATH
else:
flatc_path = native.package_relative_label(flatc_path)
reflection_include_paths = include_paths
if include_paths == None:
include_paths = default_include_paths(flatc_path)
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.
@@ -76,7 +108,7 @@ def flatbuffer_library_public(
genrule_cmd = " ".join([
"SRCS=($(SRCS));",
"for f in $${SRCS[@]:0:%s}; do" % len(srcs),
"$(location %s)" % (flatc_path),
"OUTPUT_FILE=\"$(OUTS)\" %s $(location %s)" % (extra_env, flatc_path),
" ".join(include_paths_cmd),
" ".join(flatc_args),
language_flag,
@@ -89,39 +121,49 @@ 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:
if reflection_include_paths == None:
reflection_include_paths = default_include_paths(TRUE_FLATC_PATH)
reflection_include_paths_cmd = ["-I %s" % (s) for s in reflection_include_paths]
reflection_genrule_cmd = " ".join([
"SRCS=($(SRCS));",
"for f in $${SRCS[@]:0:%s}; do" % len(srcs),
"$(location %s)" % (flatc_path),
# Move the .fbs file into the current package if it is not there already
'if [[ $$(dirname $$f) != "{0}" ]]; then s="$$f"; f="{0}/$$(basename "$$f")"; mkdir -p "{0}"; mv "$$s" "$$f"; fi;'.format(native.package_relative_label(":invalid").package),
"$(location %s)" % (TRUE_FLATC_PATH),
"-b --schema",
" ".join(flatc_args),
" ".join(include_paths_cmd),
" ".join(reflection_include_paths_cmd),
language_flag,
output_directory,
"$$f;",
"done",
])
reflection_outs = [
(out_prefix + "%s.bfbs") % (s.replace(".fbs", "").split("/")[-1])
(out_prefix + "%s.bfbs") % (native.package_relative_label(s).name.removesuffix(".fbs"))
for s in srcs
]
native.genrule(
name = "%s_srcs" % reflection_name,
srcs = srcs + includes,
outs = reflection_outs,
output_to_bindir = output_to_bindir,
tools = [flatc_path],
tools = [TRUE_FLATC_PATH],
compatible_with = compatible_with,
restricted_to = restricted_to,
target_compatible_with = target_compatible_with,
cmd = reflection_genrule_cmd,
message = "Generating flatbuffer reflection binary for %s:" % (name),
visibility = reflection_visibility,
)
native.filegroup(
name = "%s_out" % reflection_name,
@@ -135,16 +177,21 @@ def flatbuffer_cc_library(
name,
srcs,
srcs_filegroup_name = "",
outs = [],
out_prefix = "",
deps = [],
includes = [],
include_paths = DEFAULT_INCLUDE_PATHS,
include_paths = None,
cc_include_paths = [],
flatc_args = DEFAULT_FLATC_ARGS,
visibility = None,
compatible_with = None,
restricted_to = None,
filename_suffix = "_generated",
target_compatible_with = None,
srcs_filegroup_visibility = None,
gen_reflections = False):
'''A cc_library with the generated reader/writers for the given flatbuffer definitions.
"""A cc_library with the generated reader/writers for the given flatbuffer definitions.
Args:
name: Rule name.
@@ -152,11 +199,15 @@ 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
alongside includes.
includes: Optional, list of filegroups of schemas that the srcs depend on.
** SEE REMARKS BELOW **
Use of this is discouraged, and may be deprecated.
include_paths: Optional, list of paths the includes files can be found in.
cc_include_paths: Optional, list of paths to add to the cc_library includes attribute.
flatc_args: Optional list of additional arguments to pass to flatc
(e.g. --gen-mutable).
visibility: The visibility of the generated cc_library. By default, use the
@@ -169,6 +220,8 @@ def flatbuffer_cc_library(
for, in addition to default-supported environments.
restricted_to: Optional, The list of environments this rule can be built
for, instead of default-supported environments.
target_compatible_with: Optional, The list of target platform constraints
to use.
This produces:
filegroup([name]_srcs): all generated .h files.
@@ -177,48 +230,27 @@ def flatbuffer_cc_library(
parameter, if they depend on the schemas in this library.
Fileset([name]_reflection): (Optional) all generated reflection binaries.
cc_library([name]): library with sources and flatbuffers deps.
"""
Remarks:
** Because the genrule used to call flatc does not have any trivial way of
computing the output list of files transitively generated by includes and
--gen-includes (the default) being defined for flatc, the --gen-includes
flag will not work as expected. The way around this is to add a dependency
to the flatbuffer_cc_library defined alongside the flatc included Fileset.
For example you might define:
output_headers = []
for s in srcs:
base_name = s.split("/")[-1].split(":")[-1].replace(".fbs", "")
header = out_prefix + base_name + filename_suffix + ".h"
output_headers.append(header)
flatbuffer_cc_library(
name = "my_fbs",
srcs = [ "schemas/foo.fbs" ],
includes = [ "//third_party/bazz:bazz_fbs_includes" ],
)
In which foo.fbs includes a few files from the Fileset defined at
//third_party/bazz:bazz_fbs_includes. When compiling the library that
includes foo_generated.h, and therefore has my_fbs as a dependency, it
will fail to find any of the bazz *_generated.h files unless you also
add bazz's flatbuffer_cc_library to your own dependency list, e.g.:
cc_library(
name = "my_lib",
deps = [
":my_fbs",
"//third_party/bazz:bazz_fbs"
],
)
Happy dependent Flatbuffering!
'''
output_headers = [
(out_prefix + "%s_generated.h") % (s.replace(".fbs", "").split("/")[-1].split(":")[-1])
for s in srcs
]
if deps and includes:
# There is no inherent reason we couldn't support both, but this discourages
# use of includes without good reason.
fail("Cannot specify both deps and include in flatbuffer_cc_library.")
if deps:
includes = [d + "_includes" for d in deps]
reflection_name = "%s_reflection" % name if gen_reflections else ""
srcs_lib = "%s_srcs" % (name)
flatbuffer_library_public(
name = srcs_lib,
srcs = srcs,
outs = output_headers,
outs = outs + output_headers,
language_flag = "-c",
out_prefix = out_prefix,
includes = includes,
@@ -226,6 +258,7 @@ def flatbuffer_cc_library(
flatc_args = flatc_args,
compatible_with = compatible_with,
restricted_to = restricted_to,
target_compatible_with = target_compatible_with,
reflection_name = reflection_name,
reflection_visibility = visibility,
)
@@ -241,11 +274,13 @@ def flatbuffer_cc_library(
"-parse_headers",
],
deps = [
"@com_github_google_flatbuffers//:runtime_cc",
],
includes = [],
Label("//:runtime_cc"),
Label("//:flatbuffers"),
] + deps,
includes = cc_include_paths,
compatible_with = compatible_with,
restricted_to = restricted_to,
target_compatible_with = target_compatible_with,
linkstatic = 1,
visibility = visibility,
)
@@ -254,7 +289,7 @@ def flatbuffer_cc_library(
# Flatbuffer set.
native.filegroup(
name = srcs_filegroup_name if srcs_filegroup_name else "%s_includes" % (name),
srcs = srcs,
srcs = srcs + includes,
compatible_with = compatible_with,
restricted_to = restricted_to,
visibility = srcs_filegroup_visibility if srcs_filegroup_visibility != None else visibility,

View File

@@ -1,12 +0,0 @@
cmake_minimum_required(VERSION 2.8)
message(STATUS "Conan FlatBuffers Wrapper")
include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)
conan_basic_setup()
if (WIN32 AND MSVC AND FLATBUFFERS_BUILD_SHAREDLIB)
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)
endif(WIN32 AND MSVC AND FLATBUFFERS_BUILD_SHAREDLIB)
include(${CMAKE_SOURCE_DIR}/CMakeListsOriginal.txt)

View File

@@ -1,8 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
if os.getenv("APPVEYOR_REPO_TAG") != "true":
print("Skip build step. It's not TAG")
else:
os.system("python conan/build.py")

View File

@@ -1,8 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
if os.getenv("APPVEYOR_REPO_TAG") != "true":
print("Skip step. It's not TAG")
else:
os.system("pip install conan conan-package-tools")

View File

@@ -1,58 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import subprocess
from cpt.packager import ConanMultiPackager
def get_branch():
try:
for line in subprocess.check_output("git branch", shell=True).decode().splitlines():
line = line.strip()
if line.startswith("*") and " (HEAD detached" not in line:
return line.replace("*", "", 1).strip()
return ""
except Exception:
pass
return ""
def get_version():
version = get_branch()
if os.getenv("TRAVIS", False):
version = os.getenv("TRAVIS_BRANCH")
if os.getenv("APPVEYOR", False):
version = os.getenv("APPVEYOR_REPO_BRANCH")
if os.getenv("APPVEYOR_REPO_TAG") == "true":
version = os.getenv("APPVEYOR_REPO_TAG_NAME")
match = re.search(r"v(\d+\.\d+\.\d+.*)", version)
if match:
return match.group(1)
return version
def get_reference(username):
return "flatbuffers/{}@google/stable".format(get_version())
if __name__ == "__main__":
login_username = os.getenv("CONAN_LOGIN_USERNAME", "aardappel")
username = os.getenv("CONAN_USERNAME", "google")
upload = os.getenv("CONAN_UPLOAD", "https://api.bintray.com/conan/aardappel/flatbuffers")
stable_branch_pattern = os.getenv("CONAN_STABLE_BRANCH_PATTERN", r"v\d+\.\d+\.\d+.*")
test_folder = os.getenv("CPT_TEST_FOLDER", os.path.join("conan", "test_package"))
upload_only_when_stable = os.getenv("CONAN_UPLOAD_ONLY_WHEN_STABLE", True)
builder = ConanMultiPackager(reference=get_reference(username),
username=username,
login_username=login_username,
upload=upload,
stable_branch_pattern=stable_branch_pattern,
upload_only_when_stable=upload_only_when_stable,
test_folder=test_folder)
builder.add_common_builds(pure_c=False)
builder.run()

View File

@@ -1,9 +0,0 @@
project(test_package CXX)
cmake_minimum_required(VERSION 2.8.11)
include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)
conan_basic_setup()
add_executable(${PROJECT_NAME} test_package.cpp)
target_link_libraries(${PROJECT_NAME} ${CONAN_LIBS})
set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD 11)

View File

@@ -1,21 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from conans import ConanFile, CMake
import os
class TestPackageConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
generators = "cmake"
def build(self):
cmake = CMake(self)
cmake.configure()
cmake.build()
def test(self):
bin_path = os.path.join("bin", "test_package")
self.run(bin_path, run_environment=True)
self.run("flatc --version", run_environment=True)
self.run("flathash fnv1_16 conan", run_environment=True)

View File

@@ -1,35 +0,0 @@
/*
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cstdlib>
#include <iostream>
#include "flatbuffers/util.h"
// Test to validate Conan package generated
int main(int /*argc*/, const char * /*argv*/ []) {
const std::string filename("conanbuildinfo.cmake");
if (flatbuffers::FileExists(filename.c_str())) {
std::cout << "File " << filename << " exists.\n";
} else {
std::cout << "File " << filename << " does not exist.\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}

View File

@@ -1,14 +0,0 @@
#!/bin/bash
set -e
set -x
if [[ "$(uname -s)" == 'Darwin' ]]; then
if which pyenv > /dev/null; then
eval "$(pyenv init -)"
fi
pyenv activate conan
fi
conan user
python conan/build.py

View File

@@ -1,22 +0,0 @@
#!/bin/bash
set -e
set -x
if [[ "$(uname -s)" == 'Darwin' ]]; then
brew update || brew update
brew outdated pyenv || brew upgrade pyenv
brew install pyenv-virtualenv
brew install cmake || true
if which pyenv > /dev/null; then
eval "$(pyenv init -)"
fi
pyenv install 2.7.10
pyenv virtualenv 2.7.10 conan
pyenv rehash
pyenv activate conan
fi
pip install -U conan_package_tools conan

View File

@@ -1,75 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Conan recipe package for Google FlatBuffers
"""
import os
import shutil
from conans import ConanFile, CMake, tools
class FlatbuffersConan(ConanFile):
name = "flatbuffers"
license = "Apache-2.0"
url = "https://github.com/google/flatbuffers"
homepage = "http://google.github.io/flatbuffers/"
author = "Wouter van Oortmerssen"
topics = ("conan", "flatbuffers", "serialization", "rpc", "json-parser")
description = "Memory Efficient Serialization Library"
settings = "os", "compiler", "build_type", "arch"
options = {"shared": [True, False], "fPIC": [True, False]}
default_options = {"shared": False, "fPIC": True}
generators = "cmake"
exports = "LICENSE.txt"
exports_sources = ["CMake/*", "include/*", "src/*", "grpc/*", "CMakeLists.txt", "conan/CMakeLists.txt"]
def source(self):
"""Wrap the original CMake file to call conan_basic_setup
"""
shutil.move("CMakeLists.txt", "CMakeListsOriginal.txt")
shutil.move(os.path.join("conan", "CMakeLists.txt"), "CMakeLists.txt")
def config_options(self):
"""Remove fPIC option on Windows platform
"""
if self.settings.os == "Windows":
self.options.remove("fPIC")
def configure_cmake(self):
"""Create CMake instance and execute configure step
"""
cmake = CMake(self)
cmake.definitions["FLATBUFFERS_BUILD_TESTS"] = False
cmake.definitions["FLATBUFFERS_BUILD_SHAREDLIB"] = self.options.shared
cmake.definitions["FLATBUFFERS_BUILD_FLATLIB"] = not self.options.shared
cmake.configure()
return cmake
def build(self):
"""Configure, build and install FlatBuffers using CMake.
"""
cmake = self.configure_cmake()
cmake.build()
def package(self):
"""Copy Flatbuffers' artifacts to package folder
"""
cmake = self.configure_cmake()
cmake.install()
self.copy(pattern="LICENSE.txt", 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")
if self.settings.os == "Windows" and self.options.shared:
if self.settings.compiler == "Visual Studio":
shutil.move(os.path.join(self.package_folder, "lib", "%s.dll" % self.name),
os.path.join(self.package_folder, "bin", "%s.dll" % self.name))
elif self.settings.compiler == "gcc":
shutil.move(os.path.join(self.package_folder, "lib", "lib%s.dll" % self.name),
os.path.join(self.package_folder, "bin", "lib%s.dll" % self.name))
def package_info(self):
"""Collect built libraries names and solve flatc path.
"""
self.cpp_info.libs = tools.collect_libs(self)
self.user_info.flatc = os.path.join(self.package_folder, "bin", "flatc")

View File

@@ -1,3 +1,23 @@
# Changelog
## 25.9.23
- use enhanced enums (#8313)
- fix incorrect write in Float64 write method (#8290)
- code format improvements (#8707)
## 23.5.26
- omit type annotationes for local variables (#7067, #7069, #7070)
- remove BSD 3-clause license (#7073)
- correctly parse lists of enums (#7157)
- align naming conventions for generated code (#7187)
- add `putBool` to fix errors when serializing structs with booleans (#7359)
- fix handling of +/-inf defaults in codegen (#7588)
- fix import issues in generated code (#7621)
- Fix incorrect storage of floats as ints in some cases (#7703)
- add final modifiers to the library implementation (#7943)
## 2.0.5
- switch to null safety (#6696)

View File

@@ -3,7 +3,7 @@
This package is used to read and write [FlatBuffers](https://google.github.io/flatbuffers/).
Most consumers will want to use the [`flatc` - FlatBuffer compiler](https://github.com/google/flatbuffers) binary for your platform.
You can find it in the `generator/{Platform}` directory of the [released package archive](https://pub.dev/packages/flat_buffers/versions/2.0.5.tar.gz).
You can download the flatc version matching your dart package version from [GitHub releases](https://github.com/google/flatbuffers/releases).
The FlatBuffer compiler `flatc` reads a FlatBuffers IDL schema and generates Dart code.
The generated classes can be used to read or write binary data/files that are interoperable with
@@ -13,11 +13,3 @@ examples folder.
For more details and documentation, head over to the official site and read the
[Tutorial](https://google.github.io/flatbuffers/flatbuffers_guide_tutorial.html) and how to
[use FlatBuffers in Dart](https://google.github.io/flatbuffers/flatbuffers_guide_use_dart.html).
## Dart 2.0 notes
Version 2.0.5 ships with it's own custom build of `flatc` because this is an extraordinary release to catch-up
with FlatBuffers for other platforms. This generator can only generate dart code (to avoid generating code for other platforms which isn't released yet).
On the other hand, the generated code still produces standard binary FlatBuffers compatible with other languages.
In other words: only `flatc --dart ...` works with this generator, but your app will be able to produce and read standard binary (`Uint8List`) FlatBuffers that are fully compotible with other languages supporting FlatBuffers (e.g. Java, C++, ...).
In the future a common `flatc` binary for all platforms would be shipped through GitHub release page instead.

View File

@@ -15,6 +15,7 @@
*/
import 'package:flat_buffers/flat_buffers.dart' as fb;
import './monster_my_game.sample_generated.dart' as my_game;
// Example how to use FlatBuffers to create and read binary buffers.
@@ -78,7 +79,8 @@ void builderTest() {
builder.finish(monsteroff);
if (verify(builder.buffer)) {
print(
"The FlatBuffer was successfully created with a builder and verified!");
"The FlatBuffer was successfully created with a builder and verified!",
);
}
}
@@ -94,7 +96,10 @@ void objectBuilderTest() {
name: 'Orc',
inventory: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
color: my_game.Color.Red,
weapons: [my_game.WeaponObjectBuilder(name: 'Sword', damage: 3), axe],
weapons: [
my_game.WeaponObjectBuilder(name: 'Sword', damage: 3),
axe,
],
equippedType: my_game.EquipmentTypeId.Weapon,
equipped: axe,
);
@@ -108,7 +113,8 @@ void objectBuilderTest() {
// Instead, we're going to access it right away (as if we just received it).
if (verify(buffer)) {
print(
"The FlatBuffer was successfully created with an object builder and verified!");
"The FlatBuffer was successfully created with an object builder and verified!",
);
}
}

View File

@@ -4,8 +4,8 @@
library my_game.sample;
import 'dart:typed_data' show Uint8List;
import 'package:flat_buffers/flat_buffers.dart' as fb;
import 'package:flat_buffers/flat_buffers.dart' as fb;
class Color {
final int value;
@@ -19,7 +19,7 @@ class Color {
return result;
}
static Color? _createOrNull(int? value) =>
static Color? _createOrNull(int? value) =>
value == null ? null : Color.fromValue(value);
static const int minValue = 0;
@@ -29,10 +29,7 @@ class Color {
static const Color Red = Color._(0);
static const Color Green = Color._(1);
static const Color Blue = Color._(2);
static const Map<int, Color> values = {
0: Red,
1: Green,
2: Blue};
static const Map<int, Color> values = {0: Red, 1: Green, 2: Blue};
static const fb.Reader<Color> reader = _ColorReader();
@@ -60,12 +57,14 @@ class EquipmentTypeId {
factory EquipmentTypeId.fromValue(int value) {
final result = values[value];
if (result == null) {
throw StateError('Invalid value $value for bit flag enum EquipmentTypeId');
throw StateError(
'Invalid value $value for bit flag enum EquipmentTypeId',
);
}
return result;
}
static EquipmentTypeId? _createOrNull(int? value) =>
static EquipmentTypeId? _createOrNull(int? value) =>
value == null ? null : EquipmentTypeId.fromValue(value);
static const int minValue = 0;
@@ -74,9 +73,7 @@ class EquipmentTypeId {
static const EquipmentTypeId NONE = EquipmentTypeId._(0);
static const EquipmentTypeId Weapon = EquipmentTypeId._(1);
static const Map<int, EquipmentTypeId> values = {
0: NONE,
1: Weapon};
static const Map<int, EquipmentTypeId> values = {0: NONE, 1: Weapon};
static const fb.Reader<EquipmentTypeId> reader = _EquipmentTypeIdReader();
@@ -122,8 +119,7 @@ class _Vec3Reader extends fb.StructReader<Vec3> {
int get size => 12;
@override
Vec3 createObject(fb.BufferContext bc, int offset) =>
Vec3._(bc, offset);
Vec3 createObject(fb.BufferContext bc, int offset) => Vec3._(bc, offset);
}
class Vec3Builder {
@@ -137,7 +133,6 @@ class Vec3Builder {
fbBuilder.putFloat32(x);
return fbBuilder.offset;
}
}
class Vec3ObjectBuilder extends fb.ObjectBuilder {
@@ -145,14 +140,10 @@ class Vec3ObjectBuilder extends fb.ObjectBuilder {
final double _y;
final double _z;
Vec3ObjectBuilder({
required double x,
required double y,
required double z,
})
: _x = x,
_y = y,
_z = z;
Vec3ObjectBuilder({required double x, required double y, required double z})
: _x = x,
_y = y,
_z = z;
/// Finish building, and store into the [fbBuilder].
@override
@@ -171,6 +162,7 @@ class Vec3ObjectBuilder extends fb.ObjectBuilder {
return fbBuilder.buffer;
}
}
class Monster {
Monster._(this._bc, this._bcOffset);
factory Monster(List<int> bytes) {
@@ -186,18 +178,30 @@ class Monster {
Vec3? get pos => Vec3.reader.vTableGetNullable(_bc, _bcOffset, 4);
int get mana => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 6, 150);
int get hp => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 8, 100);
String? get name => const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 10);
List<int>? get inventory => const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 14);
Color get color => Color.fromValue(const fb.Int8Reader().vTableGet(_bc, _bcOffset, 16, 2));
List<Weapon>? get weapons => const fb.ListReader<Weapon>(Weapon.reader).vTableGetNullable(_bc, _bcOffset, 18);
EquipmentTypeId? get equippedType => EquipmentTypeId._createOrNull(const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 20));
String? get name =>
const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 10);
List<int>? get inventory =>
const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 14);
Color get color =>
Color.fromValue(const fb.Int8Reader().vTableGet(_bc, _bcOffset, 16, 2));
List<Weapon>? get weapons => const fb.ListReader<Weapon>(
Weapon.reader,
).vTableGetNullable(_bc, _bcOffset, 18);
EquipmentTypeId? get equippedType => EquipmentTypeId._createOrNull(
const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 20),
);
dynamic get equipped {
switch (equippedType?.value) {
case 1: return Weapon.reader.vTableGetNullable(_bc, _bcOffset, 22);
default: return null;
case 1:
return Weapon.reader.vTableGetNullable(_bc, _bcOffset, 22);
default:
return null;
}
}
List<Vec3>? get path => const fb.ListReader<Vec3>(Vec3.reader).vTableGetNullable(_bc, _bcOffset, 24);
List<Vec3>? get path => const fb.ListReader<Vec3>(
Vec3.reader,
).vTableGetNullable(_bc, _bcOffset, 24);
@override
String toString() {
@@ -209,8 +213,8 @@ class _MonsterReader extends fb.TableReader<Monster> {
const _MonsterReader();
@override
Monster createObject(fb.BufferContext bc, int offset) =>
Monster._(bc, offset);
Monster createObject(fb.BufferContext bc, int offset) =>
Monster._(bc, offset);
}
class MonsterBuilder {
@@ -226,38 +230,47 @@ class MonsterBuilder {
fbBuilder.addStruct(0, offset);
return fbBuilder.offset;
}
int addMana(int? mana) {
fbBuilder.addInt16(1, mana);
return fbBuilder.offset;
}
int addHp(int? hp) {
fbBuilder.addInt16(2, hp);
return fbBuilder.offset;
}
int addNameOffset(int? offset) {
fbBuilder.addOffset(3, offset);
return fbBuilder.offset;
}
int addInventoryOffset(int? offset) {
fbBuilder.addOffset(5, offset);
return fbBuilder.offset;
}
int addColor(Color? color) {
fbBuilder.addInt8(6, color?.value);
return fbBuilder.offset;
}
int addWeaponsOffset(int? offset) {
fbBuilder.addOffset(7, offset);
return fbBuilder.offset;
}
int addEquippedType(EquipmentTypeId? equippedType) {
fbBuilder.addUint8(8, equippedType?.value);
return fbBuilder.offset;
}
int addEquippedOffset(int? offset) {
fbBuilder.addOffset(9, offset);
return fbBuilder.offset;
}
int addPathOffset(int? offset) {
fbBuilder.addOffset(10, offset);
return fbBuilder.offset;
@@ -291,29 +304,34 @@ class MonsterObjectBuilder extends fb.ObjectBuilder {
EquipmentTypeId? equippedType,
dynamic equipped,
List<Vec3ObjectBuilder>? path,
})
: _pos = pos,
_mana = mana,
_hp = hp,
_name = name,
_inventory = inventory,
_color = color,
_weapons = weapons,
_equippedType = equippedType,
_equipped = equipped,
_path = path;
}) : _pos = pos,
_mana = mana,
_hp = hp,
_name = name,
_inventory = inventory,
_color = color,
_weapons = weapons,
_equippedType = equippedType,
_equipped = equipped,
_path = path;
/// Finish building, and store into the [fbBuilder].
@override
int finish(fb.Builder fbBuilder) {
final int? nameOffset = _name == null ? null
final int? nameOffset = _name == null
? null
: fbBuilder.writeString(_name!);
final int? inventoryOffset = _inventory == null ? null
final int? inventoryOffset = _inventory == null
? null
: fbBuilder.writeListUint8(_inventory!);
final int? weaponsOffset = _weapons == null ? null
: fbBuilder.writeList(_weapons!.map((b) => b.getOrCreateOffset(fbBuilder)).toList());
final int? weaponsOffset = _weapons == null
? null
: fbBuilder.writeList(
_weapons!.map((b) => b.getOrCreateOffset(fbBuilder)).toList(),
);
final int? equippedOffset = _equipped?.getOrCreateOffset(fbBuilder);
final int? pathOffset = _path == null ? null
final int? pathOffset = _path == null
? null
: fbBuilder.writeListOfStructs(_path!);
fbBuilder.startTable(10);
if (_pos != null) {
@@ -339,6 +357,7 @@ class MonsterObjectBuilder extends fb.ObjectBuilder {
return fbBuilder.buffer;
}
}
class Weapon {
Weapon._(this._bc, this._bcOffset);
factory Weapon(List<int> bytes) {
@@ -351,7 +370,8 @@ class Weapon {
final fb.BufferContext _bc;
final int _bcOffset;
String? get name => const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4);
String? get name =>
const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4);
int get damage => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 6, 0);
@override
@@ -364,8 +384,7 @@ class _WeaponReader extends fb.TableReader<Weapon> {
const _WeaponReader();
@override
Weapon createObject(fb.BufferContext bc, int offset) =>
Weapon._(bc, offset);
Weapon createObject(fb.BufferContext bc, int offset) => Weapon._(bc, offset);
}
class WeaponBuilder {
@@ -381,6 +400,7 @@ class WeaponBuilder {
fbBuilder.addOffset(0, offset);
return fbBuilder.offset;
}
int addDamage(int? damage) {
fbBuilder.addInt16(1, damage);
return fbBuilder.offset;
@@ -395,17 +415,15 @@ class WeaponObjectBuilder extends fb.ObjectBuilder {
final String? _name;
final int? _damage;
WeaponObjectBuilder({
String? name,
int? damage,
})
: _name = name,
_damage = damage;
WeaponObjectBuilder({String? name, int? damage})
: _name = name,
_damage = damage;
/// Finish building, and store into the [fbBuilder].
@override
int finish(fb.Builder fbBuilder) {
final int? nameOffset = _name == null ? null
final int? nameOffset = _name == null
? null
: fbBuilder.writeString(_name!);
fbBuilder.startTable(2);
fbBuilder.addOffset(0, nameOffset);

View File

@@ -1,7 +1,3 @@
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:collection';
import 'dart:convert';
import 'dart:math';
@@ -31,10 +27,11 @@ class BufferContext {
ByteData get buffer => _buffer;
/// Create from a FlatBuffer represented by a list of bytes (uint8).
factory BufferContext.fromBytes(List<int> byteList) =>
BufferContext(byteList is Uint8List
? byteList.buffer.asByteData(byteList.offsetInBytes)
: ByteData.view(Uint8List.fromList(byteList).buffer));
factory BufferContext.fromBytes(List<int> byteList) => BufferContext(
byteList is Uint8List
? byteList.buffer.asByteData(byteList.offsetInBytes)
: ByteData.view(Uint8List.fromList(byteList).buffer),
);
/// Create from a FlatBuffer represented by ByteData.
BufferContext(this._buffer);
@@ -153,9 +150,9 @@ class Builder {
bool internStrings = false,
Allocator allocator = const DefaultAllocator(),
this.deduplicateTables = true,
}) : _allocator = allocator,
_buf = allocator.allocate(initialSize),
_vTables = deduplicateTables ? [] : const [] {
}) : _allocator = allocator,
_buf = allocator.allocate(initialSize),
_vTables = deduplicateTables ? [] : const [] {
if (internStrings) {
_strings = <String, int>{};
}
@@ -308,7 +305,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;
@@ -354,8 +351,10 @@ class Builder {
Uint8List get buffer {
assert(_finished);
final finishedSize = size();
return _buf.buffer
.asUint8List(_buf.lengthInBytes - finishedSize, finishedSize);
return _buf.buffer.asUint8List(
_buf.lengthInBytes - finishedSize,
finishedSize,
);
}
/// Finish off the creation of the buffer. The given [offset] is used as the
@@ -372,14 +371,18 @@ class Builder {
if (fileIdentifier != null) {
for (var i = 0; i < 4; i++) {
_setUint8AtTail(
finishedSize - _sizeofUint32 - i, fileIdentifier.codeUnitAt(i));
finishedSize - _sizeofUint32 - i,
fileIdentifier.codeUnitAt(i),
);
}
}
// zero out the added padding
for (var i = sizeBeforePadding + 1;
i <= finishedSize - requiredBytes;
i++) {
for (
var i = sizeBeforePadding + 1;
i <= finishedSize - requiredBytes;
i++
) {
_setUint8AtTail(i, 0);
}
_finished = true;
@@ -390,7 +393,7 @@ class Builder {
/// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer.
void putFloat64(double value) {
_prepare(_sizeofFloat64, 1);
_setFloat32AtTail(_tail, value);
_setFloat64AtTail(_tail, value);
}
/// Writes a Float32 to the tail of the buffer after preparing space for it.
@@ -401,6 +404,15 @@ class Builder {
_setFloat32AtTail(_tail, value);
}
/// Writes a bool to the tail of the buffer after preparing space for it.
/// Bools are represented as a Uint8, with the value set to '1' for true, and '0' for false
///
/// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer.
void putBool(bool value) {
_prepare(_sizeofUint8, 1);
_buf.setInt8(_buf.lengthInBytes - _tail, value ? 1 : 0);
}
/// Writes a Int64 to the tail of the buffer after preparing space for it.
///
/// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer.
@@ -509,7 +521,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;
}
@@ -524,7 +536,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;
}
@@ -539,7 +551,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;
}
@@ -554,7 +566,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;
}
@@ -569,7 +581,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;
}
@@ -584,7 +596,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;
}
@@ -599,7 +611,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;
}
@@ -614,7 +626,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;
}
@@ -629,7 +641,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;
}
@@ -649,7 +661,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;
}
@@ -664,7 +676,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;
}
@@ -682,8 +694,10 @@ class Builder {
int writeString(String value, {bool asciiOptimization = false}) {
assert(!_inVTable);
if (_strings != null) {
return _strings!
.putIfAbsent(value, () => _writeString(value, asciiOptimization));
return _strings!.putIfAbsent(
value,
() => _writeString(value, asciiOptimization),
);
} else {
return _writeString(value, asciiOptimization);
}
@@ -772,17 +786,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);
}
}
@@ -1000,8 +1014,11 @@ class ListReader<E> extends Reader<List<E>> {
: List<E>.generate(
bc.buffer.getUint32(listOffset, Endian.little),
(int index) => _elementReader.read(
bc, listOffset + size + _elementReader.size * index),
growable: true);
bc,
listOffset + size + _elementReader.size * index,
),
growable: true,
);
}
}
@@ -1018,22 +1035,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);
}
@@ -1052,9 +1069,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);
}
@@ -1063,7 +1080,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;
@@ -1099,7 +1116,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);
}
}
@@ -1279,7 +1296,7 @@ class _FbGenericList<E> extends _FbList<E> {
List<E?>? _items;
_FbGenericList(this.elementReader, BufferContext bp, int offset)
: super(bp, offset);
: super(bp, offset);
@override
@pragma('vm:prefer-inline')
@@ -1449,7 +1466,11 @@ abstract class Allocator {
/// Params [inUseBack] and [inUseFront] indicate how much of [oldData] is
/// actually in use at each end, and needs to be copied.
ByteData resize(
ByteData oldData, int newSize, int inUseBack, int inUseFront) {
ByteData oldData,
int newSize,
int inUseBack,
int inUseFront,
) {
final newData = allocate(newSize);
_copyDownward(oldData, newData, inUseBack, inUseFront);
deallocate(oldData);
@@ -1460,17 +1481,25 @@ abstract class Allocator {
/// memory of size [inUseFront] and [inUseBack] will be copied from the front
/// and back of the old memory allocation.
void _copyDownward(
ByteData oldData, ByteData newData, int inUseBack, int inUseFront) {
ByteData oldData,
ByteData newData,
int inUseBack,
int inUseFront,
) {
if (inUseBack != 0) {
newData.buffer.asUint8List().setAll(
newData.lengthInBytes - inUseBack,
oldData.buffer.asUint8List().getRange(
oldData.lengthInBytes - inUseBack, oldData.lengthInBytes));
newData.lengthInBytes - inUseBack,
oldData.buffer.asUint8List().getRange(
oldData.lengthInBytes - inUseBack,
oldData.lengthInBytes,
),
);
}
if (inUseFront != 0) {
newData.buffer
.asUint8List()
.setAll(0, oldData.buffer.asUint8List().getRange(0, inUseFront));
newData.buffer.asUint8List().setAll(
0,
oldData.buffer.asUint8List().getRange(0, inUseFront),
);
}
}
}

View File

@@ -17,7 +17,7 @@ class Builder {
final Map<double, _StackValue> _indirectDoubleCache = {};
/// Instantiate the builder if you intent to gradually build up the buffer by calling
/// add... methods and calling [finish] to receive the the resulting byte array.
/// add... methods and calling [finish] to receive the resulting byte array.
///
/// The default size of internal buffer is set to 2048. Provide a different value in order to avoid buffer copies.
Builder({int size = 2048}) : _buffer = ByteData(size);
@@ -107,8 +107,11 @@ class Builder {
final newOffset = _newOffset(length + 1);
_pushBuffer(utf8String);
_offset = newOffset;
final stackValue =
_StackValue.withOffset(stringOffset, ValueType.String, bitWidth);
final stackValue = _StackValue.withOffset(
stringOffset,
ValueType.String,
bitWidth,
);
_stack.add(stackValue);
_stringCache[value] = stackValue;
}
@@ -128,8 +131,11 @@ class Builder {
final newOffset = _newOffset(length + 1);
_pushBuffer(utf8String);
_offset = newOffset;
final stackValue =
_StackValue.withOffset(keyOffset, ValueType.Key, BitWidth.width8);
final stackValue = _StackValue.withOffset(
keyOffset,
ValueType.Key,
BitWidth.width8,
);
_stack.add(stackValue);
_keyCache[value] = stackValue;
}
@@ -147,8 +153,11 @@ class Builder {
final newOffset = _newOffset(length);
_pushBuffer(value.asUint8List());
_offset = newOffset;
final stackValue =
_StackValue.withOffset(blobOffset, ValueType.Blob, bitWidth);
final stackValue = _StackValue.withOffset(
blobOffset,
ValueType.Blob,
bitWidth,
);
_stack.add(stackValue);
}
@@ -170,7 +179,10 @@ class Builder {
final valueOffset = _offset;
_pushBuffer(stackValue.asU8List(stackValue.width));
final stackOffset = _StackValue.withOffset(
valueOffset, ValueType.IndirectInt, stackValue.width);
valueOffset,
ValueType.IndirectInt,
stackValue.width,
);
_stack.add(stackOffset);
_offset = newOffset;
if (cache) {
@@ -195,7 +207,10 @@ class Builder {
final valueOffset = _offset;
_pushBuffer(stackValue.asU8List(stackValue.width));
final stackOffset = _StackValue.withOffset(
valueOffset, ValueType.IndirectFloat, stackValue.width);
valueOffset,
ValueType.IndirectFloat,
stackValue.width,
);
_stack.add(stackOffset);
_offset = newOffset;
if (cache) {
@@ -252,9 +267,10 @@ class Builder {
tmp._offset = _offset;
tmp._stack = List.from(_stack);
tmp._stackPointers = List.from(_stackPointers);
tmp._buffer.buffer
.asUint8List()
.setAll(0, _buffer.buffer.asUint8List(0, _offset));
tmp._buffer.buffer.asUint8List().setAll(
0,
_buffer.buffer.asUint8List(0, _offset),
);
for (var i = 0; i < tmp._stackPointers.length; i++) {
tmp.end();
}
@@ -271,7 +287,8 @@ class Builder {
if (_stackPointers.isNotEmpty && _stackPointers.last.isVector == false) {
if (_stack.last.type != ValueType.Key) {
throw StateError(
'Adding value to a map before adding a key is prohibited');
'Adding value to a map before adding a key is prohibited',
);
}
}
}
@@ -288,7 +305,8 @@ class Builder {
void _finish() {
if (_stack.length != 1) {
throw StateError(
'Stack has to be exactly 1, but is ${_stack.length}. You have to end all started vectors and maps, before calling [finish]');
'Stack has to be exactly 1, but is ${_stack.length}. You have to end all started vectors and maps, before calling [finish]',
);
}
final value = _stack[0];
final byteWidth = _align(value.elementWidth(_offset, 0));
@@ -298,8 +316,12 @@ class Builder {
_finished = true;
}
_StackValue _createVector(int start, int vecLength, int step,
[_StackValue? keys]) {
_StackValue _createVector(
int start,
int vecLength,
int step, [
_StackValue? keys,
]) {
var bitWidth = BitWidthUtil.uwidth(vecLength);
var prefixElements = 1;
if (keys != null) {
@@ -326,7 +348,8 @@ class Builder {
}
}
final byteWidth = _align(bitWidth);
final fix = typed & ValueTypeUtils.isNumber(vectorType) &&
final fix =
typed & ValueTypeUtils.isNumber(vectorType) &&
vecLength >= 2 &&
vecLength <= 4;
if (keys != null) {
@@ -349,8 +372,10 @@ class Builder {
return _StackValue.withOffset(vecOffset, ValueType.Map, bitWidth);
}
if (typed) {
final vType =
ValueTypeUtils.toTypedVector(vectorType, fix ? vecLength : 0);
final vType = ValueTypeUtils.toTypedVector(
vectorType,
fix ? vecLength : 0,
);
return _StackValue.withOffset(vecOffset, vType, bitWidth);
}
return _StackValue.withOffset(vecOffset, ValueType.Vector, bitWidth);
@@ -366,7 +391,8 @@ class Builder {
void _sortKeysAndEndMap(_StackPointer pointer) {
if (((_stack.length - pointer.stackPosition) & 1) == 1) {
throw StateError(
'The stack needs to hold key value pairs (even number of elements). Check if you combined [addKey] with add... method calls properly.');
'The stack needs to hold key value pairs (even number of elements). Check if you combined [addKey] with add... method calls properly.',
);
}
var sorted = true;
@@ -412,8 +438,12 @@ class Builder {
keysStackValue = _createVector(pointer.stackPosition, vecLength, 2);
_keyVectorCache[keysHash] = keysStackValue;
}
final vec =
_createVector(pointer.stackPosition + 1, vecLength, 2, keysStackValue);
final vec = _createVector(
pointer.stackPosition + 1,
vecLength,
2,
keysStackValue,
);
_stack.removeRange(pointer.stackPosition, _stack.length);
_stack.add(vec);
}
@@ -421,7 +451,8 @@ class Builder {
bool _shouldFlip(_StackValue v1, _StackValue v2) {
if (v1.type != ValueType.Key || v2.type != ValueType.Key) {
throw StateError(
'Stack values are not keys $v1 | $v2. Check if you combined [addKey] with add... method calls properly.');
'Stack values are not keys $v1 | $v2. Check if you combined [addKey] with add... method calls properly.',
);
}
late int c1, c2;
@@ -450,7 +481,8 @@ class Builder {
_writeUInt(relativeOffset, byteWidth);
} else {
throw StateError(
'Unexpected size $byteWidth. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new');
'Unexpected size $byteWidth. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new',
);
}
} else {
_pushBuffer(value.asU8List(BitWidthUtil.fromByteWidth(byteWidth)));
@@ -523,29 +555,27 @@ class _StackValue {
final ValueType _type;
final BitWidth _width;
_StackValue.withNull()
: _type = ValueType.Null,
_width = BitWidth.width8;
_StackValue.withNull() : _type = ValueType.Null, _width = BitWidth.width8;
_StackValue.withInt(int value)
: _type = ValueType.Int,
_width = BitWidthUtil.width(value),
_value = value;
: _type = ValueType.Int,
_width = BitWidthUtil.width(value),
_value = value;
_StackValue.withBool(bool value)
: _type = ValueType.Bool,
_width = BitWidth.width8,
_value = value;
: _type = ValueType.Bool,
_width = BitWidth.width8,
_value = value;
_StackValue.withDouble(double value)
: _type = ValueType.Float,
_width = BitWidthUtil.width(value),
_value = value;
: _type = ValueType.Float,
_width = BitWidthUtil.width(value),
_value = value;
_StackValue.withOffset(int value, ValueType type, BitWidth width)
: _offset = value,
_type = type,
_width = width;
: _offset = value,
_type = type,
_width = width;
BitWidth storedWidth({BitWidth width = BitWidth.width8}) {
return ValueTypeUtils.isInline(_type)
@@ -562,16 +592,16 @@ class _StackValue {
final offset = _offset!;
for (var i = 0; i < 4; i++) {
final width = 1 << i;
final bitWidth = BitWidthUtil.uwidth(size +
BitWidthUtil.paddingSize(size, width) +
index * width -
offset);
final bitWidth = BitWidthUtil.uwidth(
size + BitWidthUtil.paddingSize(size, width) + index * width - offset,
);
if (1 << bitWidth.index == width) {
return bitWidth;
}
}
throw StateError(
'Element is of unknown. Size: $size at index: $index. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new');
'Element is of unknown. Size: $size at index: $index. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new',
);
}
List<int> asU8List(BitWidth width) {
@@ -619,7 +649,8 @@ class _StackValue {
}
throw StateError(
'Unexpected type: $_type. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new');
'Unexpected type: $_type. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new',
);
}
ValueType get type {

View File

@@ -1,6 +1,7 @@
import 'dart:collection';
import 'dart:convert';
import 'dart:typed_data';
import 'types.dart';
/// Main class to read a value out of a FlexBuffer.
@@ -16,10 +17,15 @@ class Reference {
int? _length;
Reference._(
this._buffer, this._offset, this._parentWidth, int packedType, this._path,
[int? byteWidth, ValueType? valueType])
: _byteWidth = byteWidth ?? 1 << (packedType & 3),
_valueType = valueType ?? ValueTypeUtils.fromInt(packedType >> 2);
this._buffer,
this._offset,
this._parentWidth,
int packedType,
this._path, [
int? byteWidth,
ValueType? valueType,
]) : _byteWidth = byteWidth ?? 1 << (packedType & 3),
_valueType = valueType ?? ValueTypeUtils.fromInt(packedType >> 2);
/// Use this method to access the root value of a FlexBuffer.
static Reference fromBuffer(ByteBuffer buffer) {
@@ -31,8 +37,13 @@ class Reference {
final byteWidth = byteData.getUint8(len - 1);
final packedType = byteData.getUint8(len - 2);
final offset = len - byteWidth - 2;
return Reference._(ByteData.view(buffer), offset,
BitWidthUtil.fromByteWidth(byteWidth), packedType, "/");
return Reference._(
ByteData.view(buffer),
offset,
BitWidthUtil.fromByteWidth(byteWidth),
packedType,
"/",
);
}
/// Returns true if the underlying value is null.
@@ -138,7 +149,8 @@ class Reference {
final index = key;
if (index >= length || index < 0) {
throw ArgumentError(
'Key: [$key] is not applicable on: $_path of: $_valueType length: $length');
'Key: [$key] is not applicable on: $_path of: $_valueType length: $length',
);
}
final elementOffset = _indirect + index * _byteWidth;
int packedType = 0;
@@ -154,13 +166,14 @@ class Reference {
packedType = _buffer.getUint8(_indirect + length * _byteWidth + index);
}
return Reference._(
_buffer,
elementOffset,
BitWidthUtil.fromByteWidth(_byteWidth),
packedType,
"$_path[$index]",
byteWidth,
valueType);
_buffer,
elementOffset,
BitWidthUtil.fromByteWidth(_byteWidth),
packedType,
"$_path[$index]",
byteWidth,
valueType,
);
}
if (key is String && _valueType == ValueType.Map) {
final index = _keyIndex(key);
@@ -169,7 +182,8 @@ class Reference {
}
}
throw ArgumentError(
'Key: [$key] is not applicable on: $_path of: $_valueType');
'Key: [$key] is not applicable on: $_path of: $_valueType',
);
}
/// Get an iterable if the underlying flexBuffer value is a vector.
@@ -199,7 +213,7 @@ class Reference {
return _MapValueIterator(this);
}
/// Returns the length of the the underlying FlexBuffer value.
/// Returns the length of the underlying FlexBuffer value.
/// If the underlying value is [null] the length is 0.
/// If the underlying value is a number, or a bool, the length is 1.
/// If the underlying value is a vector, or map, the length reflects number of elements / element pairs.
@@ -213,18 +227,24 @@ class Reference {
ValueTypeUtils.isAVector(_valueType) ||
_valueType == ValueType.Map) {
_length = _readUInt(
_indirect - _byteWidth, BitWidthUtil.fromByteWidth(_byteWidth));
_indirect - _byteWidth,
BitWidthUtil.fromByteWidth(_byteWidth),
);
} else if (_valueType == ValueType.Null) {
_length = 0;
} else if (_valueType == ValueType.String) {
final indirect = _indirect;
var sizeByteWidth = _byteWidth;
var size = _readUInt(indirect - sizeByteWidth,
BitWidthUtil.fromByteWidth(sizeByteWidth));
var size = _readUInt(
indirect - sizeByteWidth,
BitWidthUtil.fromByteWidth(sizeByteWidth),
);
while (_buffer.getInt8(indirect + size) != 0) {
sizeByteWidth <<= 1;
size = _readUInt(indirect - sizeByteWidth,
BitWidthUtil.fromByteWidth(sizeByteWidth));
size = _readUInt(
indirect - sizeByteWidth,
BitWidthUtil.fromByteWidth(sizeByteWidth),
);
}
_length = size;
} else if (_valueType == ValueType.Key) {
@@ -289,7 +309,8 @@ class Reference {
return result.toString();
}
throw UnsupportedError(
'Type: $_valueType is not supported for JSON conversion');
'Type: $_valueType is not supported for JSON conversion',
);
}
/// Computes the indirect offset of the value.
@@ -354,10 +375,13 @@ class Reference {
int? _keyIndex(String key) {
final input = utf8.encode(key);
final keysVectorOffset = _indirect - _byteWidth * 3;
final indirectOffset = keysVectorOffset -
final indirectOffset =
keysVectorOffset -
_readUInt(keysVectorOffset, BitWidthUtil.fromByteWidth(_byteWidth));
final byteWidth = _readUInt(
keysVectorOffset + _byteWidth, BitWidthUtil.fromByteWidth(_byteWidth));
keysVectorOffset + _byteWidth,
BitWidthUtil.fromByteWidth(_byteWidth),
);
var low = 0;
var high = length - 1;
while (low <= high) {
@@ -390,24 +414,37 @@ class Reference {
final indirect = _indirect;
final elementOffset = indirect + index * _byteWidth;
final packedType = _buffer.getUint8(indirect + length * _byteWidth + index);
return Reference._(_buffer, elementOffset,
BitWidthUtil.fromByteWidth(_byteWidth), packedType, "$_path/$key");
return Reference._(
_buffer,
elementOffset,
BitWidthUtil.fromByteWidth(_byteWidth),
packedType,
"$_path/$key",
);
}
Reference _valueForIndex(int index) {
final indirect = _indirect;
final elementOffset = indirect + index * _byteWidth;
final packedType = _buffer.getUint8(indirect + length * _byteWidth + index);
return Reference._(_buffer, elementOffset,
BitWidthUtil.fromByteWidth(_byteWidth), packedType, "$_path/[$index]");
return Reference._(
_buffer,
elementOffset,
BitWidthUtil.fromByteWidth(_byteWidth),
packedType,
"$_path/[$index]",
);
}
String _keyForIndex(int index) {
final keysVectorOffset = _indirect - _byteWidth * 3;
final indirectOffset = keysVectorOffset -
final indirectOffset =
keysVectorOffset -
_readUInt(keysVectorOffset, BitWidthUtil.fromByteWidth(_byteWidth));
final byteWidth = _readUInt(
keysVectorOffset + _byteWidth, BitWidthUtil.fromByteWidth(_byteWidth));
keysVectorOffset + _byteWidth,
BitWidthUtil.fromByteWidth(_byteWidth),
);
final keyOffset = indirectOffset + index * byteWidth;
final keyIndirectOffset =
keyOffset - _readUInt(keyOffset, BitWidthUtil.fromByteWidth(byteWidth));

View File

@@ -9,7 +9,7 @@ class BitWidthUtil {
}
static BitWidth width(num value) {
if (value.toInt() == value) {
if (value is int) {
var v = value.toInt().abs();
if (v >> 7 == 0) return BitWidth.width8;
if (v >> 15 == 0) return BitWidth.width16;
@@ -86,7 +86,8 @@ enum ValueType {
VectorFloat,
VectorKey,
@Deprecated(
'VectorString is deprecated due to a flaw in the binary format (https://github.com/google/flatbuffers/issues/5627)')
'VectorString is deprecated due to a flaw in the binary format (https://github.com/google/flatbuffers/issues/5627)',
)
VectorString,
VectorInt2,
VectorUInt2,
@@ -99,7 +100,7 @@ enum ValueType {
VectorFloat4,
Blob,
Bool,
VectorBool
VectorBool,
}
class ValueTypeUtils {
@@ -153,31 +154,37 @@ class ValueTypeUtils {
static ValueType toTypedVector(ValueType self, int length) {
if (length == 0) {
return ValueTypeUtils.fromInt(
toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt));
toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt),
);
}
if (length == 2) {
return ValueTypeUtils.fromInt(
toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt2));
toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt2),
);
}
if (length == 3) {
return ValueTypeUtils.fromInt(
toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt3));
toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt3),
);
}
if (length == 4) {
return ValueTypeUtils.fromInt(
toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt4));
toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt4),
);
}
throw Exception('unexpected length ' + length.toString());
}
static ValueType typedVectorElementType(ValueType self) {
return ValueTypeUtils.fromInt(
toInt(self) - toInt(ValueType.VectorInt) + toInt(ValueType.Int));
toInt(self) - toInt(ValueType.VectorInt) + toInt(ValueType.Int),
);
}
static ValueType fixedTypedVectorElementType(ValueType self) {
return ValueTypeUtils.fromInt(
(toInt(self) - toInt(ValueType.VectorInt2)) % 3 + toInt(ValueType.Int));
(toInt(self) - toInt(ValueType.VectorInt2)) % 3 + toInt(ValueType.Int),
);
}
static int fixedTypedVectorElementSize(ValueType self) {

View File

@@ -1,15 +1,14 @@
name: flat_buffers
version: 2.0.5
version: 25.12.19
description: FlatBuffers reading and writing library for Dart. Based on original work by Konstantin Scheglov and Paul Berry of the Dart SDK team.
homepage: https://github.com/google/flatbuffers
documentation: https://google.github.io/flatbuffers/index.html
environment:
sdk: '>=2.12.0 <3.0.0'
sdk: '>=2.17.0 <4.0.0'
dev_dependencies:
test: ^1.17.7
test_reflective_loader: ^0.2.0
path: ^1.8.0
lints: ^1.0.1

View File

@@ -0,0 +1,10 @@
// Test for #7355
table Foo {
my_foo : foo_properties;
}
struct foo_properties
{
a : bool;
b : bool;
}

View File

@@ -0,0 +1,195 @@
// automatically generated by the FlatBuffers compiler, do not modify
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names
import 'dart:typed_data' show Uint8List;
import 'package:flat_buffers/flat_buffers.dart' as fb;
class Foo {
Foo._(this._bc, this._bcOffset);
factory Foo(List<int> bytes) {
final rootRef = fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}
static const fb.Reader<Foo> reader = _FooReader();
final fb.BufferContext _bc;
final int _bcOffset;
FooProperties? get myFoo =>
FooProperties.reader.vTableGetNullable(_bc, _bcOffset, 4);
@override
String toString() {
return 'Foo{myFoo: ${myFoo}}';
}
FooT unpack() => FooT(myFoo: myFoo?.unpack());
static int pack(fb.Builder fbBuilder, FooT? object) {
if (object == null) return 0;
return object.pack(fbBuilder);
}
}
class FooT implements fb.Packable {
FooPropertiesT? myFoo;
FooT({this.myFoo});
@override
int pack(fb.Builder fbBuilder) {
fbBuilder.startTable(1);
if (myFoo != null) {
fbBuilder.addStruct(0, myFoo!.pack(fbBuilder));
}
return fbBuilder.endTable();
}
@override
String toString() {
return 'FooT{myFoo: ${myFoo}}';
}
}
class _FooReader extends fb.TableReader<Foo> {
const _FooReader();
@override
Foo createObject(fb.BufferContext bc, int offset) => Foo._(bc, offset);
}
class FooBuilder {
FooBuilder(this.fbBuilder);
final fb.Builder fbBuilder;
void begin() {
fbBuilder.startTable(1);
}
int addMyFoo(int offset) {
fbBuilder.addStruct(0, offset);
return fbBuilder.offset;
}
int finish() {
return fbBuilder.endTable();
}
}
class FooObjectBuilder extends fb.ObjectBuilder {
final FooPropertiesObjectBuilder? _myFoo;
FooObjectBuilder({FooPropertiesObjectBuilder? myFoo}) : _myFoo = myFoo;
/// Finish building, and store into the [fbBuilder].
@override
int finish(fb.Builder fbBuilder) {
fbBuilder.startTable(1);
if (_myFoo != null) {
fbBuilder.addStruct(0, _myFoo!.finish(fbBuilder));
}
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 FooProperties {
FooProperties._(this._bc, this._bcOffset);
static const fb.Reader<FooProperties> reader = _FooPropertiesReader();
final fb.BufferContext _bc;
final int _bcOffset;
bool get a => const fb.BoolReader().read(_bc, _bcOffset + 0);
bool get b => const fb.BoolReader().read(_bc, _bcOffset + 1);
@override
String toString() {
return 'FooProperties{a: ${a}, b: ${b}}';
}
FooPropertiesT unpack() => FooPropertiesT(a: a, b: b);
static int pack(fb.Builder fbBuilder, FooPropertiesT? object) {
if (object == null) return 0;
return object.pack(fbBuilder);
}
}
class FooPropertiesT implements fb.Packable {
bool a;
bool b;
FooPropertiesT({required this.a, required this.b});
@override
int pack(fb.Builder fbBuilder) {
fbBuilder.putBool(b);
fbBuilder.putBool(a);
return fbBuilder.offset;
}
@override
String toString() {
return 'FooPropertiesT{a: ${a}, b: ${b}}';
}
}
class _FooPropertiesReader extends fb.StructReader<FooProperties> {
const _FooPropertiesReader();
@override
int get size => 2;
@override
FooProperties createObject(fb.BufferContext bc, int offset) =>
FooProperties._(bc, offset);
}
class FooPropertiesBuilder {
FooPropertiesBuilder(this.fbBuilder);
final fb.Builder fbBuilder;
int finish(bool a, bool b) {
fbBuilder.putBool(b);
fbBuilder.putBool(a);
return fbBuilder.offset;
}
}
class FooPropertiesObjectBuilder extends fb.ObjectBuilder {
final bool _a;
final bool _b;
FooPropertiesObjectBuilder({required bool a, required bool b})
: _a = a,
_b = b;
/// Finish building, and store into the [fbBuilder].
@override
int finish(fb.Builder fbBuilder) {
fbBuilder.putBool(_b);
fbBuilder.putBool(_a);
return fbBuilder.offset;
}
/// 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
dart/test/enums.fbs Normal file
View File

@@ -0,0 +1,10 @@
enum OptionsEnum : uint32
{
A = 1,
B = 2,
C = 3
}
table MyTable {
options : [OptionsEnum];
}

View File

@@ -0,0 +1,153 @@
// automatically generated by the FlatBuffers compiler, do not modify
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names
import 'dart:typed_data' show Uint8List;
import 'package:flat_buffers/flat_buffers.dart' as fb;
enum OptionsEnum {
A(1),
B(2),
C(3);
final int value;
const OptionsEnum(this.value);
factory OptionsEnum.fromValue(int value) {
switch (value) {
case 1:
return OptionsEnum.A;
case 2:
return OptionsEnum.B;
case 3:
return OptionsEnum.C;
default:
throw StateError('Invalid value $value for bit flag enum');
}
}
static OptionsEnum? _createOrNull(int? value) =>
value == null ? null : OptionsEnum.fromValue(value);
static const int minValue = 1;
static const int maxValue = 3;
static const fb.Reader<OptionsEnum> reader = _OptionsEnumReader();
}
class _OptionsEnumReader extends fb.Reader<OptionsEnum> {
const _OptionsEnumReader();
@override
int get size => 4;
@override
OptionsEnum read(fb.BufferContext bc, int offset) =>
OptionsEnum.fromValue(const fb.Uint32Reader().read(bc, offset));
}
class MyTable {
MyTable._(this._bc, this._bcOffset);
factory MyTable(List<int> bytes) {
final rootRef = fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}
static const fb.Reader<MyTable> reader = _MyTableReader();
final fb.BufferContext _bc;
final int _bcOffset;
List<OptionsEnum>? get options => const fb.ListReader<OptionsEnum>(
OptionsEnum.reader,
).vTableGetNullable(_bc, _bcOffset, 4);
@override
String toString() {
return 'MyTable{options: ${options}}';
}
MyTableT unpack() => MyTableT(
options: const fb.ListReader<OptionsEnum>(
OptionsEnum.reader,
lazy: false,
).vTableGetNullable(_bc, _bcOffset, 4),
);
static int pack(fb.Builder fbBuilder, MyTableT? object) {
if (object == null) return 0;
return object.pack(fbBuilder);
}
}
class MyTableT implements fb.Packable {
List<OptionsEnum>? options;
MyTableT({this.options});
@override
int pack(fb.Builder fbBuilder) {
final int? optionsOffset = options == null
? null
: fbBuilder.writeListUint32(options!.map((f) => f.value).toList());
fbBuilder.startTable(1);
fbBuilder.addOffset(0, optionsOffset);
return fbBuilder.endTable();
}
@override
String toString() {
return 'MyTableT{options: ${options}}';
}
}
class _MyTableReader extends fb.TableReader<MyTable> {
const _MyTableReader();
@override
MyTable createObject(fb.BufferContext bc, int offset) =>
MyTable._(bc, offset);
}
class MyTableBuilder {
MyTableBuilder(this.fbBuilder);
final fb.Builder fbBuilder;
void begin() {
fbBuilder.startTable(1);
}
int addOptionsOffset(int? offset) {
fbBuilder.addOffset(0, offset);
return fbBuilder.offset;
}
int finish() {
return fbBuilder.endTable();
}
}
class MyTableObjectBuilder extends fb.ObjectBuilder {
final List<OptionsEnum>? _options;
MyTableObjectBuilder({List<OptionsEnum>? options}) : _options = options;
/// Finish building, and store into the [fbBuilder].
@override
int finish(fb.Builder fbBuilder) {
final int? optionsOffset = _options == null
? null
: fbBuilder.writeListUint32(_options!.map((f) => f.value).toList());
fbBuilder.startTable(1);
fbBuilder.addOffset(0, optionsOffset);
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;
}
}

View File

@@ -1,18 +1,15 @@
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:typed_data';
import 'dart:io' as io;
import 'package:path/path.dart' as path;
import 'dart:typed_data';
import 'package:flat_buffers/flat_buffers.dart';
import 'package:path/path.dart' as path;
import 'package:test/test.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
import './monster_test_my_game.example_generated.dart' as example;
import './bool_structs_generated.dart' as example4;
import './monster_test_my_game.example2_generated.dart' as example2;
import './monster_test_my_game.example_generated.dart' as example;
import 'enums_generated.dart' as example3;
main() {
defineReflectiveSuite(() {
@@ -20,6 +17,7 @@ main() {
defineReflectiveTests(ObjectAPITest);
defineReflectiveTests(CheckOtherLangaugesData);
defineReflectiveTests(GeneratorTest);
defineReflectiveTests(ListOfEnumsTest);
});
}
@@ -30,11 +28,9 @@ int indexToField(int index) {
@reflectiveTest
class CheckOtherLangaugesData {
test_cppData() async {
List<int> data = await io.File(path.join(
path.context.current,
'test',
'monsterdata_test.mon',
)).readAsBytes();
List<int> data = await io.File(
path.join(path.context.current, 'test', 'monsterdata_test.mon'),
).readAsBytes();
example.Monster mon = example.Monster(data);
expect(mon.hp, 80);
expect(mon.mana, 150);
@@ -64,11 +60,11 @@ class CheckOtherLangaugesData {
expect(
mon.toString(),
'Monster{'
'pos: Vec3{x: 1.0, y: 2.0, z: 3.0, test1: 3.0, test2: Color{value: 2}, test3: Test{a: 5, b: 6}}, '
'pos: Vec3{x: 1.0, y: 2.0, z: 3.0, test1: 3.0, test2: Color.Green, test3: Test{a: 5, b: 6}}, '
'mana: 150, hp: 80, name: MyMonster, inventory: [0, 1, 2, 3, 4], '
'color: Color{value: 8}, testType: AnyTypeId{value: 1}, '
'color: Color.Blue, testType: AnyTypeId.Monster, '
'test: Monster{pos: null, mana: 150, hp: 100, name: Fred, '
'inventory: null, color: Color{value: 8}, testType: null, '
'inventory: null, color: Color.Blue, testType: null, '
'test: null, test4: null, testarrayofstring: null, '
'testarrayoftables: null, enemy: null, testnestedflatbuffer: null, '
'testempty: null, testbool: false, testhashs32Fnv1: 0, '
@@ -83,13 +79,18 @@ class CheckOtherLangaugesData {
'coOwningReference: 0, vectorOfCoOwningReferences: null, '
'nonOwningReference: 0, vectorOfNonOwningReferences: null, '
'anyUniqueType: null, anyUnique: null, anyAmbiguousType: null, '
'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race{value: -1}, '
'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race.None, '
'testrequirednestedflatbuffer: null, scalarKeySortedTables: null, '
'nativeInline: null}, '
'nativeInline: null, '
'longEnumNonEnumDefault: LongEnum._default, '
'longEnumNormalDefault: LongEnum.LongOne, nanDefault: NaN, '
'infDefault: Infinity, positiveInfDefault: Infinity, infinityDefault: '
'Infinity, positiveInfinityDefault: Infinity, negativeInfDefault: '
'-Infinity, negativeInfinityDefault: -Infinity, doubleInfDefault: Infinity}, '
'test4: [Test{a: 10, b: 20}, Test{a: 30, b: 40}], '
'testarrayofstring: [test1, test2], testarrayoftables: null, '
'enemy: Monster{pos: null, mana: 150, hp: 100, name: Fred, '
'inventory: null, color: Color{value: 8}, testType: null, '
'inventory: null, color: Color.Blue, testType: null, '
'test: null, test4: null, testarrayofstring: null, '
'testarrayoftables: null, enemy: null, testnestedflatbuffer: null, '
'testempty: null, testbool: false, testhashs32Fnv1: 0, '
@@ -104,9 +105,14 @@ class CheckOtherLangaugesData {
'coOwningReference: 0, vectorOfCoOwningReferences: null, '
'nonOwningReference: 0, vectorOfNonOwningReferences: null, '
'anyUniqueType: null, anyUnique: null, anyAmbiguousType: null, '
'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race{value: -1}, '
'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race.None, '
'testrequirednestedflatbuffer: null, scalarKeySortedTables: null, '
'nativeInline: null}, '
'nativeInline: null, '
'longEnumNonEnumDefault: LongEnum._default, '
'longEnumNormalDefault: LongEnum.LongOne, nanDefault: NaN, '
'infDefault: Infinity, positiveInfDefault: Infinity, infinityDefault: '
'Infinity, positiveInfinityDefault: Infinity, negativeInfDefault: '
'-Infinity, negativeInfinityDefault: -Infinity, doubleInfDefault: Infinity}, '
'testnestedflatbuffer: null, testempty: null, testbool: true, '
'testhashs32Fnv1: -579221183, testhashu32Fnv1: 3715746113, '
'testhashs64Fnv1: 7930699090847568257, '
@@ -128,10 +134,15 @@ class CheckOtherLangaugesData {
'vectorOfNonOwningReferences: null, '
'anyUniqueType: null, anyUnique: null, '
'anyAmbiguousType: null, '
'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race{value: -1}, '
'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race.None, '
'testrequirednestedflatbuffer: null, scalarKeySortedTables: [Stat{id: '
'miss, val: 0, count: 0}, Stat{id: hit, val: 10, count: 1}], '
'nativeInline: Test{a: 1, b: 2}}',
'nativeInline: Test{a: 1, b: 2}, '
'longEnumNonEnumDefault: LongEnum._default, '
'longEnumNormalDefault: LongEnum.LongOne, nanDefault: NaN, '
'infDefault: Infinity, positiveInfDefault: Infinity, infinityDefault: '
'Infinity, positiveInfinityDefault: Infinity, negativeInfDefault: '
'-Infinity, negativeInfinityDefault: -Infinity, doubleInfDefault: Infinity}',
);
}
}
@@ -202,6 +213,10 @@ class BuilderTest {
..addTestarrayofstringOffset(testArrayOfString);
final mon = monBuilder.finish();
fbBuilder.finish(mon);
final mon3 = example.Monster(fbBuilder.buffer);
expect(mon3.name, 'MyMonster');
expect(mon3.pos!.test1, 3.0);
}
void test_error_addInt32_withoutStartTable([Builder? builder]) {
@@ -281,20 +296,72 @@ class BuilderTest {
expect(allocator.buffer(builder.size()), [2, 0, 0, 0, 0, 0, 0, 1]);
builder.putUint8(3);
expect(
allocator.buffer(builder.size()), [0, 0, 0, 3, 2, 0, 0, 0, 0, 0, 0, 1]);
expect(allocator.buffer(builder.size()), [
0,
0,
0,
3,
2,
0,
0,
0,
0,
0,
0,
1,
]);
builder.putUint8(4);
expect(
allocator.buffer(builder.size()), [0, 0, 4, 3, 2, 0, 0, 0, 0, 0, 0, 1]);
expect(allocator.buffer(builder.size()), [
0,
0,
4,
3,
2,
0,
0,
0,
0,
0,
0,
1,
]);
builder.putUint8(5);
expect(
allocator.buffer(builder.size()), [0, 5, 4, 3, 2, 0, 0, 0, 0, 0, 0, 1]);
expect(allocator.buffer(builder.size()), [
0,
5,
4,
3,
2,
0,
0,
0,
0,
0,
0,
1,
]);
builder.putUint32(6);
expect(allocator.buffer(builder.size()),
[6, 0, 0, 0, 0, 5, 4, 3, 2, 0, 0, 0, 0, 0, 0, 1]);
expect(allocator.buffer(builder.size()), [
6,
0,
0,
0,
0,
5,
4,
3,
2,
0,
0,
0,
0,
0,
0,
1,
]);
}
void test_table_default() {
@@ -314,14 +381,14 @@ class BuilderTest {
int objectOffset = buffer.derefObject(0);
// was not written, so uses the new default value
expect(
const Int32Reader()
.vTableGet(buffer, objectOffset, indexToField(0), 15),
15);
const Int32Reader().vTableGet(buffer, objectOffset, indexToField(0), 15),
15,
);
// has the written value
expect(
const Int32Reader()
.vTableGet(buffer, objectOffset, indexToField(1), 15),
20);
const Int32Reader().vTableGet(buffer, objectOffset, indexToField(1), 15),
20,
);
}
void test_table_format([Builder? builder]) {
@@ -353,7 +420,9 @@ class BuilderTest {
for (int i = 0; i < 3; i++) {
int offset = byteData.getUint16(vTableLoc + 4 + 2 * i, Endian.little);
expect(
byteData.getInt32(tableDataLoc + offset, Endian.little), 10 + 10 * i);
byteData.getInt32(tableDataLoc + offset, Endian.little),
10 + 10 * i,
);
}
}
@@ -363,10 +432,14 @@ class BuilderTest {
List<int> byteList;
{
Builder builder = Builder(initialSize: 0);
int? latinStringOffset =
builder.writeString(latinString, asciiOptimization: true);
int? unicodeStringOffset =
builder.writeString(unicodeString, asciiOptimization: true);
int? latinStringOffset = builder.writeString(
latinString,
asciiOptimization: true,
);
int? unicodeStringOffset = builder.writeString(
unicodeString,
asciiOptimization: true,
);
builder.startTable(2);
builder.addOffset(0, latinStringOffset);
builder.addOffset(1, unicodeStringOffset);
@@ -378,13 +451,19 @@ class BuilderTest {
BufferContext buf = BufferContext.fromBytes(byteList);
int objectOffset = buf.derefObject(0);
expect(
const StringReader()
.vTableGetNullable(buf, objectOffset, indexToField(0)),
latinString);
const StringReader().vTableGetNullable(
buf,
objectOffset,
indexToField(0),
),
latinString,
);
expect(
const StringReader(asciiOptimization: true)
.vTableGetNullable(buf, objectOffset, indexToField(1)),
unicodeString);
const StringReader(
asciiOptimization: true,
).vTableGetNullable(buf, objectOffset, indexToField(1)),
unicodeString,
);
}
void test_table_types([Builder? builder]) {
@@ -408,33 +487,41 @@ class BuilderTest {
BufferContext buf = BufferContext.fromBytes(byteList);
int objectOffset = buf.derefObject(0);
expect(
const BoolReader()
.vTableGetNullable(buf, objectOffset, indexToField(0)),
true);
const BoolReader().vTableGetNullable(buf, objectOffset, indexToField(0)),
true,
);
expect(
const Int8Reader()
.vTableGetNullable(buf, objectOffset, indexToField(1)),
10);
const Int8Reader().vTableGetNullable(buf, objectOffset, indexToField(1)),
10,
);
expect(
const Int32Reader()
.vTableGetNullable(buf, objectOffset, indexToField(2)),
20);
const Int32Reader().vTableGetNullable(buf, objectOffset, indexToField(2)),
20,
);
expect(
const StringReader()
.vTableGetNullable(buf, objectOffset, indexToField(3)),
'12345');
const StringReader().vTableGetNullable(
buf,
objectOffset,
indexToField(3),
),
'12345',
);
expect(
const Int32Reader()
.vTableGetNullable(buf, objectOffset, indexToField(4)),
40);
const Int32Reader().vTableGetNullable(buf, objectOffset, indexToField(4)),
40,
);
expect(
const Uint32Reader()
.vTableGetNullable(buf, objectOffset, indexToField(5)),
0x9ABCDEF0);
const Uint32Reader().vTableGetNullable(
buf,
objectOffset,
indexToField(5),
),
0x9ABCDEF0,
);
expect(
const Uint8Reader()
.vTableGetNullable(buf, objectOffset, indexToField(6)),
0x9A);
const Uint8Reader().vTableGetNullable(buf, objectOffset, indexToField(6)),
0x9A,
);
}
void test_writeList_of_Uint32() {
@@ -579,8 +666,9 @@ class BuilderTest {
}
// read and verify
BufferContext buf = BufferContext.fromBytes(byteList);
List<TestPointImpl> items =
const ListReader<TestPointImpl>(TestPointReader()).read(buf, 0);
List<TestPointImpl> items = const ListReader<TestPointImpl>(
TestPointReader(),
).read(buf, 0);
expect(items, hasLength(2));
expect(items[0].x, 10);
expect(items[0].y, 20);
@@ -610,8 +698,10 @@ class BuilderTest {
List<int> byteList;
{
builder ??= Builder(initialSize: 0);
int listOffset = builder.writeList(
[builder.writeString('12345'), builder.writeString('ABC')]);
int listOffset = builder.writeList([
builder.writeString('12345'),
builder.writeString('ABC'),
]);
builder.startTable(1);
builder.addOffset(0, listOffset);
int offset = builder.endTable();
@@ -690,13 +780,14 @@ class BuilderTest {
test_table_format,
test_table_types,
test_writeList_ofObjects,
test_writeList_ofStrings_inObject
test_writeList_ofStrings_inObject,
];
// Execute all test cases in all permutations of their order.
// To do that, we generate permutations of test case indexes.
final testCasesPermutations =
_permutationsOf(List.generate(testCases.length, (index) => index));
final testCasesPermutations = _permutationsOf(
List.generate(testCases.length, (index) => index),
);
expect(testCasesPermutations.length, _factorial(testCases.length));
for (var indexes in testCasesPermutations) {
@@ -754,7 +845,6 @@ class BuilderTest {
class ObjectAPITest {
void test_tableStat() {
final object1 = example.StatT(count: 3, id: "foo", val: 4);
expect(object1 is Packable, isTrue);
final fbb = Builder();
fbb.finish(object1.pack(fbb));
final object2 = example.Stat(fbb.buffer).unpack();
@@ -767,28 +857,28 @@ class ObjectAPITest {
void test_tableMonster() {
final monster = example.MonsterT()
..pos = example.Vec3T(
x: 1,
y: 2,
z: 3,
test1: 4.0,
test2: example.Color.Red,
test3: example.TestT(a: 1, b: 2))
x: 1,
y: 2,
z: 3,
test1: 4.0,
test2: example.Color.Red,
test3: example.TestT(a: 1, b: 2),
)
..mana = 2
..name = 'Monstrous'
..inventory = [24, 42]
..color = example.Color.Green
// TODO be smarter for unions and automatically set the `type` field?
..testType = example.AnyTypeId.MyGame_Example2_Monster
..test = example2.MonsterT()
..test4 = [example.TestT(a: 3, b: 4), example.TestT(a: 5, b: 6)]
..testarrayofstring = ["foo", "bar"]
..testarrayoftables = [example.MonsterT(name: 'Oof')]
..enemy = example.MonsterT(name: 'Enemy')
..testarrayoftables = [example.MonsterT(name: 'Oof', testf: 2.75)]
..enemy = example.MonsterT(name: 'Enemy', testf: 2.5)
..testarrayofbools = [false, true, false]
..testf = 42.24
..testf = 42.25
..testarrayofsortedstruct = [
example.AbilityT(id: 1, distance: 5),
example.AbilityT(id: 3, distance: 7)
example.AbilityT(id: 3, distance: 7),
]
..vectorOfLongs = [5, 6, 7]
..vectorOfDoubles = [8.9, 9.0, 10.1, 11.2]
@@ -803,16 +893,15 @@ class ObjectAPITest {
fbBuilder.finish(offset);
final data = fbBuilder.buffer;
// TODO currently broken because of struct builder issue, see #6688
// final monster2 = example.Monster(data); // Monster (reader)
// expect(
// // map Monster => MonsterT, Vec3 => Vec3T, ...
// monster2.toString().replaceAllMapped(
// RegExp('([a-zA-z0-9]+){'), (match) => match.group(1) + 'T{'),
// monster.toString());
//
// final monster3 = monster2.unpack(); // MonsterT
// expect(monster3.toString(), monster.toString());
final monster2 = example.Monster(data); // Monster (reader)
expect(
// map Monster => MonsterT, Vec3 => Vec3T, ...
monster2.toString().replaceAllMapped(
RegExp('([a-zA-z0-9]+){'), (match) => match.group(1)! + 'T{'),
monster.toString());
final monster3 = monster2.unpack(); // MonsterT
expect(monster3.toString(), monster.toString());
}
void test_Lists() {
@@ -851,8 +940,9 @@ class StringListWrapperImpl {
StringListWrapperImpl(this.bp, this.offset);
List<String>? get items => const ListReader<String>(StringReader())
.vTableGetNullable(bp, offset, indexToField(0));
List<String>? get items => const ListReader<String>(
StringReader(),
).vTableGetNullable(bp, offset, indexToField(0));
}
class StringListWrapperReader extends TableReader<StringListWrapperImpl> {
@@ -890,9 +980,45 @@ class GeneratorTest {
expect(example.Color.values, same(example.Color.values));
expect(example.Race.values, same(example.Race.values));
expect(example.AnyTypeId.values, same(example.AnyTypeId.values));
expect(example.AnyUniqueAliasesTypeId.values,
same(example.AnyUniqueAliasesTypeId.values));
expect(example.AnyAmbiguousAliasesTypeId.values,
same(example.AnyAmbiguousAliasesTypeId.values));
expect(
example.AnyUniqueAliasesTypeId.values,
same(example.AnyUniqueAliasesTypeId.values),
);
expect(
example.AnyAmbiguousAliasesTypeId.values,
same(example.AnyAmbiguousAliasesTypeId.values),
);
}
}
// See #6869
@reflectiveTest
class ListOfEnumsTest {
void test_listOfEnums() async {
var mytable = example3.MyTableObjectBuilder(
options: [
example3.OptionsEnum.A,
example3.OptionsEnum.B,
example3.OptionsEnum.C,
],
);
var bytes = mytable.toBytes();
var mytable_read = example3.MyTable(bytes);
expect(mytable_read.options![0].value, example3.OptionsEnum.A.value);
expect(mytable_read.options![1].value, example3.OptionsEnum.B.value);
expect(mytable_read.options![2].value, example3.OptionsEnum.C.value);
}
}
@reflectiveTest
class BoolInStructTest {
void test_boolInStruct() async {
var mystruct = example4.FooObjectBuilder(
myFoo: example4.FooPropertiesObjectBuilder(a: true, b: false),
);
var bytes = mystruct.toBytes();
var mystruct_read = example4.Foo(bytes);
expect(mystruct_read.myFoo!.a, true);
expect(mystruct_read.myFoo!.b, false);
}
}

View File

@@ -40,6 +40,10 @@ void main() {
flx.addInt(-1025);
expect(flx.finish(), [255, 251, 5, 2]);
}
{
var builder = Builder()..addDouble(1.0);
expect(builder.finish(), [0, 0, 128, 63, 14, 4]);
}
{
var flx = Builder();
flx.addDouble(0.1);
@@ -58,8 +62,23 @@ void main() {
{
var flx = Builder();
flx.addString('hello 😱');
expect(flx.finish(),
[10, 104, 101, 108, 108, 111, 32, 240, 159, 152, 177, 0, 11, 20, 1]);
expect(flx.finish(), [
10,
104,
101,
108,
108,
111,
32,
240,
159,
152,
177,
0,
11,
20,
1,
]);
}
});
@@ -113,7 +132,7 @@ void main() {
192,
16,
75,
1
1,
]);
}
{
@@ -173,7 +192,7 @@ void main() {
7,
3,
60,
1
1,
]);
}
{
@@ -211,7 +230,7 @@ void main() {
10,
6,
60,
1
1,
]);
}
{
@@ -296,7 +315,7 @@ void main() {
104,
45,
43,
1
1,
]);
}
});
@@ -318,8 +337,24 @@ void main() {
..addKey('')
..addInt(45)
..end();
expect(
flx.finish(), [97, 0, 0, 2, 2, 5, 2, 1, 2, 45, 12, 4, 4, 4, 36, 1]);
expect(flx.finish(), [
97,
0,
0,
2,
2,
5,
2,
1,
2,
45,
12,
4,
4,
4,
36,
1,
]);
}
{
var flx = Builder()
@@ -363,7 +398,7 @@ void main() {
36,
4,
40,
1
1,
]);
}
});
@@ -377,133 +412,152 @@ void main() {
test('build from object', () {
expect(
Builder.buildFromObject(Uint8List.fromList([1, 2, 3]).buffer)
.asUint8List(),
[3, 1, 2, 3, 3, 100, 1]);
Builder.buildFromObject(
Uint8List.fromList([1, 2, 3]).buffer,
).asUint8List(),
[3, 1, 2, 3, 3, 100, 1],
);
expect(Builder.buildFromObject(null).asUint8List(), [0, 0, 1]);
expect(Builder.buildFromObject(true).asUint8List(), [1, 104, 1]);
expect(Builder.buildFromObject(false).asUint8List(), [0, 104, 1]);
expect(Builder.buildFromObject(25).asUint8List(), [25, 4, 1]);
expect(Builder.buildFromObject(-250).asUint8List(), [6, 255, 5, 2]);
expect(Builder.buildFromObject(-2.50).asUint8List(), [
0,
0,
32,
192,
14,
4,
]);
expect(Builder.buildFromObject('Maxim').asUint8List(), [
5,
77,
97,
120,
105,
109,
0,
6,
20,
1,
]);
expect(
Builder.buildFromObject(-2.50).asUint8List(), [0, 0, 32, 192, 14, 4]);
expect(Builder.buildFromObject('Maxim').asUint8List(),
[5, 77, 97, 120, 105, 109, 0, 6, 20, 1]);
Builder.buildFromObject([1, 3.3, 'max', true, null, false]).asUint8List(),
[
3,
109,
97,
120,
0,
0,
0,
0,
6,
0,
0,
0,
0,
0,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
102,
102,
102,
102,
102,
102,
10,
64,
31,
0,
0,
0,
0,
0,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
4,
15,
20,
104,
0,
104,
54,
43,
1,
],
);
expect(
Builder.buildFromObject([1, 3.3, 'max', true, null, false])
.asUint8List(),
[
3,
109,
97,
120,
0,
0,
0,
0,
6,
0,
0,
0,
0,
0,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
102,
102,
102,
102,
102,
102,
10,
64,
31,
0,
0,
0,
0,
0,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
4,
15,
20,
104,
0,
104,
54,
43,
1
]);
expect(
Builder.buildFromObject([
{'something': 12},
{'something': 45}
]).asUint8List(),
[
115,
111,
109,
101,
116,
104,
105,
110,
103,
0,
1,
11,
1,
1,
1,
12,
4,
6,
1,
1,
45,
4,
2,
8,
4,
36,
36,
4,
40,
1
]);
Builder.buildFromObject([
{'something': 12},
{'something': 45},
]).asUint8List(),
[
115,
111,
109,
101,
116,
104,
105,
110,
103,
0,
1,
11,
1,
1,
1,
12,
4,
6,
1,
1,
45,
4,
2,
8,
4,
36,
36,
4,
40,
1,
],
);
});
test('add double indirectly', () {
@@ -539,7 +593,7 @@ void main() {
35,
8,
40,
1
1,
]);
});
@@ -576,7 +630,7 @@ void main() {
27,
8,
40,
1
1,
]);
});

File diff suppressed because it is too large Load Diff

View File

@@ -48,116 +48,210 @@ void main() {
expect(ValueTypeUtils.isFixedTypedVector(ValueType.VectorInt), isFalse);
});
test('to typed vector', () {
expect(ValueTypeUtils.toTypedVector(ValueType.Int, 0),
equals(ValueType.VectorInt));
expect(ValueTypeUtils.toTypedVector(ValueType.UInt, 0),
equals(ValueType.VectorUInt));
expect(ValueTypeUtils.toTypedVector(ValueType.Bool, 0),
equals(ValueType.VectorBool));
expect(ValueTypeUtils.toTypedVector(ValueType.Float, 0),
equals(ValueType.VectorFloat));
expect(ValueTypeUtils.toTypedVector(ValueType.Key, 0),
equals(ValueType.VectorKey));
expect(ValueTypeUtils.toTypedVector(ValueType.String, 0),
equals(ValueType.VectorString));
expect(
ValueTypeUtils.toTypedVector(ValueType.Int, 0),
equals(ValueType.VectorInt),
);
expect(
ValueTypeUtils.toTypedVector(ValueType.UInt, 0),
equals(ValueType.VectorUInt),
);
expect(
ValueTypeUtils.toTypedVector(ValueType.Bool, 0),
equals(ValueType.VectorBool),
);
expect(
ValueTypeUtils.toTypedVector(ValueType.Float, 0),
equals(ValueType.VectorFloat),
);
expect(
ValueTypeUtils.toTypedVector(ValueType.Key, 0),
equals(ValueType.VectorKey),
);
expect(
ValueTypeUtils.toTypedVector(ValueType.String, 0),
equals(ValueType.VectorString),
);
expect(ValueTypeUtils.toTypedVector(ValueType.Int, 2),
equals(ValueType.VectorInt2));
expect(ValueTypeUtils.toTypedVector(ValueType.UInt, 2),
equals(ValueType.VectorUInt2));
expect(ValueTypeUtils.toTypedVector(ValueType.Float, 2),
equals(ValueType.VectorFloat2));
expect(
ValueTypeUtils.toTypedVector(ValueType.Int, 2),
equals(ValueType.VectorInt2),
);
expect(
ValueTypeUtils.toTypedVector(ValueType.UInt, 2),
equals(ValueType.VectorUInt2),
);
expect(
ValueTypeUtils.toTypedVector(ValueType.Float, 2),
equals(ValueType.VectorFloat2),
);
expect(ValueTypeUtils.toTypedVector(ValueType.Int, 3),
equals(ValueType.VectorInt3));
expect(ValueTypeUtils.toTypedVector(ValueType.UInt, 3),
equals(ValueType.VectorUInt3));
expect(ValueTypeUtils.toTypedVector(ValueType.Float, 3),
equals(ValueType.VectorFloat3));
expect(
ValueTypeUtils.toTypedVector(ValueType.Int, 3),
equals(ValueType.VectorInt3),
);
expect(
ValueTypeUtils.toTypedVector(ValueType.UInt, 3),
equals(ValueType.VectorUInt3),
);
expect(
ValueTypeUtils.toTypedVector(ValueType.Float, 3),
equals(ValueType.VectorFloat3),
);
expect(ValueTypeUtils.toTypedVector(ValueType.Int, 4),
equals(ValueType.VectorInt4));
expect(ValueTypeUtils.toTypedVector(ValueType.UInt, 4),
equals(ValueType.VectorUInt4));
expect(ValueTypeUtils.toTypedVector(ValueType.Float, 4),
equals(ValueType.VectorFloat4));
expect(
ValueTypeUtils.toTypedVector(ValueType.Int, 4),
equals(ValueType.VectorInt4),
);
expect(
ValueTypeUtils.toTypedVector(ValueType.UInt, 4),
equals(ValueType.VectorUInt4),
);
expect(
ValueTypeUtils.toTypedVector(ValueType.Float, 4),
equals(ValueType.VectorFloat4),
);
});
test('typed vector element type', () {
expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorInt),
equals(ValueType.Int));
expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorUInt),
equals(ValueType.UInt));
expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorFloat),
equals(ValueType.Float));
expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorString),
equals(ValueType.String));
expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorKey),
equals(ValueType.Key));
expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorBool),
equals(ValueType.Bool));
expect(
ValueTypeUtils.typedVectorElementType(ValueType.VectorInt),
equals(ValueType.Int),
);
expect(
ValueTypeUtils.typedVectorElementType(ValueType.VectorUInt),
equals(ValueType.UInt),
);
expect(
ValueTypeUtils.typedVectorElementType(ValueType.VectorFloat),
equals(ValueType.Float),
);
expect(
ValueTypeUtils.typedVectorElementType(ValueType.VectorString),
equals(ValueType.String),
);
expect(
ValueTypeUtils.typedVectorElementType(ValueType.VectorKey),
equals(ValueType.Key),
);
expect(
ValueTypeUtils.typedVectorElementType(ValueType.VectorBool),
equals(ValueType.Bool),
);
});
test('fixed typed vector element type', () {
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt2),
equals(ValueType.Int));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt3),
equals(ValueType.Int));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt4),
equals(ValueType.Int));
expect(
ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt2),
equals(ValueType.Int),
);
expect(
ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt3),
equals(ValueType.Int),
);
expect(
ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt4),
equals(ValueType.Int),
);
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt2),
equals(ValueType.UInt));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt3),
equals(ValueType.UInt));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt4),
equals(ValueType.UInt));
expect(
ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt2),
equals(ValueType.UInt),
);
expect(
ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt3),
equals(ValueType.UInt),
);
expect(
ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt4),
equals(ValueType.UInt),
);
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat2),
equals(ValueType.Float));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat3),
equals(ValueType.Float));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat4),
equals(ValueType.Float));
expect(
ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat2),
equals(ValueType.Float),
);
expect(
ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat3),
equals(ValueType.Float),
);
expect(
ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat4),
equals(ValueType.Float),
);
});
test('fixed typed vector element size', () {
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt2),
equals(2));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt3),
equals(3));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt4),
equals(4));
expect(
ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt2),
equals(2),
);
expect(
ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt3),
equals(3),
);
expect(
ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt4),
equals(4),
);
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt2),
equals(2));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt3),
equals(3));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt4),
equals(4));
expect(
ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt2),
equals(2),
);
expect(
ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt3),
equals(3),
);
expect(
ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt4),
equals(4),
);
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat2),
equals(2));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat3),
equals(3));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat4),
equals(4));
expect(
ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat2),
equals(2),
);
expect(
ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat3),
equals(3),
);
expect(
ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat4),
equals(4),
);
});
test('packed type', () {
expect(
ValueTypeUtils.packedType(ValueType.Null, BitWidth.width8), equals(0));
ValueTypeUtils.packedType(ValueType.Null, BitWidth.width8),
equals(0),
);
expect(
ValueTypeUtils.packedType(ValueType.Null, BitWidth.width16), equals(1));
ValueTypeUtils.packedType(ValueType.Null, BitWidth.width16),
equals(1),
);
expect(
ValueTypeUtils.packedType(ValueType.Null, BitWidth.width32), equals(2));
ValueTypeUtils.packedType(ValueType.Null, BitWidth.width32),
equals(2),
);
expect(
ValueTypeUtils.packedType(ValueType.Null, BitWidth.width64), equals(3));
ValueTypeUtils.packedType(ValueType.Null, BitWidth.width64),
equals(3),
);
expect(
ValueTypeUtils.packedType(ValueType.Int, BitWidth.width8), equals(4));
ValueTypeUtils.packedType(ValueType.Int, BitWidth.width8),
equals(4),
);
expect(
ValueTypeUtils.packedType(ValueType.Int, BitWidth.width16), equals(5));
ValueTypeUtils.packedType(ValueType.Int, BitWidth.width16),
equals(5),
);
expect(
ValueTypeUtils.packedType(ValueType.Int, BitWidth.width32), equals(6));
ValueTypeUtils.packedType(ValueType.Int, BitWidth.width32),
equals(6),
);
expect(
ValueTypeUtils.packedType(ValueType.Int, BitWidth.width64), equals(7));
ValueTypeUtils.packedType(ValueType.Int, BitWidth.width64),
equals(7),
);
});
test('bit width', () {
expect(BitWidthUtil.width(0), BitWidth.width8);

View File

@@ -0,0 +1,108 @@
// automatically generated by the FlatBuffers compiler, do not modify
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names
import 'dart:typed_data' show Uint8List;
import 'package:flat_buffers/flat_buffers.dart' as fb;
import './include_test2_my_game.other_name_space_generated.dart'
as my_game_other_name_space;
class TableA {
TableA._(this._bc, this._bcOffset);
factory TableA(List<int> bytes) {
final rootRef = fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}
static const fb.Reader<TableA> reader = _TableAReader();
final fb.BufferContext _bc;
final int _bcOffset;
my_game_other_name_space.TableB? get b => my_game_other_name_space
.TableB
.reader
.vTableGetNullable(_bc, _bcOffset, 4);
@override
String toString() {
return 'TableA{b: ${b}}';
}
TableAT unpack() => TableAT(b: b?.unpack());
static int pack(fb.Builder fbBuilder, TableAT? object) {
if (object == null) return 0;
return object.pack(fbBuilder);
}
}
class TableAT implements fb.Packable {
my_game_other_name_space.TableBT? b;
TableAT({this.b});
@override
int pack(fb.Builder fbBuilder) {
final int? bOffset = b?.pack(fbBuilder);
fbBuilder.startTable(1);
fbBuilder.addOffset(0, bOffset);
return fbBuilder.endTable();
}
@override
String toString() {
return 'TableAT{b: ${b}}';
}
}
class _TableAReader extends fb.TableReader<TableA> {
const _TableAReader();
@override
TableA createObject(fb.BufferContext bc, int offset) => TableA._(bc, offset);
}
class TableABuilder {
TableABuilder(this.fbBuilder);
final fb.Builder fbBuilder;
void begin() {
fbBuilder.startTable(1);
}
int addBOffset(int? offset) {
fbBuilder.addOffset(0, offset);
return fbBuilder.offset;
}
int finish() {
return fbBuilder.endTable();
}
}
class TableAObjectBuilder extends fb.ObjectBuilder {
final my_game_other_name_space.TableBObjectBuilder? _b;
TableAObjectBuilder({my_game_other_name_space.TableBObjectBuilder? b})
: _b = b;
/// Finish building, and store into the [fbBuilder].
@override
int finish(fb.Builder fbBuilder) {
final int? bOffset = _b?.getOrCreateOffset(fbBuilder);
fbBuilder.startTable(1);
fbBuilder.addOffset(0, bOffset);
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;
}
}

View File

@@ -0,0 +1,221 @@
// automatically generated by the FlatBuffers compiler, do not modify
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names
library my_game.other_name_space;
import 'dart:typed_data' show Uint8List;
import 'package:flat_buffers/flat_buffers.dart' as fb;
import './include_test1_generated.dart';
enum FromInclude {
IncludeVal(0);
final int value;
const FromInclude(this.value);
factory FromInclude.fromValue(int value) {
switch (value) {
case 0:
return FromInclude.IncludeVal;
default:
throw StateError('Invalid value $value for bit flag enum');
}
}
static FromInclude? _createOrNull(int? value) =>
value == null ? null : FromInclude.fromValue(value);
static const int minValue = 0;
static const int maxValue = 0;
static const fb.Reader<FromInclude> reader = _FromIncludeReader();
}
class _FromIncludeReader extends fb.Reader<FromInclude> {
const _FromIncludeReader();
@override
int get size => 8;
@override
FromInclude read(fb.BufferContext bc, int offset) =>
FromInclude.fromValue(const fb.Int64Reader().read(bc, offset));
}
class Unused {
Unused._(this._bc, this._bcOffset);
static const fb.Reader<Unused> reader = _UnusedReader();
final fb.BufferContext _bc;
final int _bcOffset;
int get a => const fb.Int32Reader().read(_bc, _bcOffset + 0);
@override
String toString() {
return 'Unused{a: ${a}}';
}
UnusedT unpack() => UnusedT(a: a);
static int pack(fb.Builder fbBuilder, UnusedT? object) {
if (object == null) return 0;
return object.pack(fbBuilder);
}
}
class UnusedT implements fb.Packable {
int a;
UnusedT({required this.a});
@override
int pack(fb.Builder fbBuilder) {
fbBuilder.putInt32(a);
return fbBuilder.offset;
}
@override
String toString() {
return 'UnusedT{a: ${a}}';
}
}
class _UnusedReader extends fb.StructReader<Unused> {
const _UnusedReader();
@override
int get size => 4;
@override
Unused createObject(fb.BufferContext bc, int offset) => Unused._(bc, offset);
}
class UnusedBuilder {
UnusedBuilder(this.fbBuilder);
final fb.Builder fbBuilder;
int finish(int a) {
fbBuilder.putInt32(a);
return fbBuilder.offset;
}
}
class UnusedObjectBuilder extends fb.ObjectBuilder {
final int _a;
UnusedObjectBuilder({required int a}) : _a = a;
/// Finish building, and store into the [fbBuilder].
@override
int finish(fb.Builder fbBuilder) {
fbBuilder.putInt32(_a);
return fbBuilder.offset;
}
/// 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 TableB {
TableB._(this._bc, this._bcOffset);
factory TableB(List<int> bytes) {
final rootRef = fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}
static const fb.Reader<TableB> reader = _TableBReader();
final fb.BufferContext _bc;
final int _bcOffset;
TableA? get a => TableA.reader.vTableGetNullable(_bc, _bcOffset, 4);
@override
String toString() {
return 'TableB{a: ${a}}';
}
TableBT unpack() => TableBT(a: a?.unpack());
static int pack(fb.Builder fbBuilder, TableBT? object) {
if (object == null) return 0;
return object.pack(fbBuilder);
}
}
class TableBT implements fb.Packable {
TableAT? a;
TableBT({this.a});
@override
int pack(fb.Builder fbBuilder) {
final int? aOffset = a?.pack(fbBuilder);
fbBuilder.startTable(1);
fbBuilder.addOffset(0, aOffset);
return fbBuilder.endTable();
}
@override
String toString() {
return 'TableBT{a: ${a}}';
}
}
class _TableBReader extends fb.TableReader<TableB> {
const _TableBReader();
@override
TableB createObject(fb.BufferContext bc, int offset) => TableB._(bc, offset);
}
class TableBBuilder {
TableBBuilder(this.fbBuilder);
final fb.Builder fbBuilder;
void begin() {
fbBuilder.startTable(1);
}
int addAOffset(int? offset) {
fbBuilder.addOffset(0, offset);
return fbBuilder.offset;
}
int finish() {
return fbBuilder.endTable();
}
}
class TableBObjectBuilder extends fb.ObjectBuilder {
final TableAObjectBuilder? _a;
TableBObjectBuilder({TableAObjectBuilder? a}) : _a = a;
/// Finish building, and store into the [fbBuilder].
@override
int finish(fb.Builder fbBuilder) {
final int? aOffset = _a?.getOrCreateOffset(fbBuilder);
fbBuilder.startTable(1);
fbBuilder.addOffset(0, aOffset);
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;
}
}

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