Compare commits

...

164 Commits

Author SHA1 Message Date
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
856 changed files with 49925 additions and 17358 deletions

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

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

16
.github/labeler.yml vendored
View File

@@ -15,11 +15,15 @@ c#:
swift:
- '**/*.swift'
- swift/**/*
- tests/FlatBuffers.GRPC.Swift/**/*
- tests/FlatBuffers.Benchmarks.swift/**/*
- tests/FlatBuffers.Test.Swift/**/*
- tests/swift/**
- src/idl_gen_swift.cpp
nim:
- '**/*.nim'
- nim/**/*
- src/idl_gen_nim.cpp
- src/bfbs_gen_nim.cpp
javascript:
- '**/*.js'
- src/idl_gen_ts.cpp
@@ -63,7 +67,7 @@ rust:
- '**/*.rs'
- rust/**/*
- src/idl_gen_rust.cpp
dart:
- '**/*.dart'
- src/idl_gen_dart.cpp
@@ -86,10 +90,8 @@ documentation:
CI:
- '.github/**/*'
- '.travis/**/*'
- '.bazelci/**/*'
- .travis.yml
grpc:
- grpc/**/*
- src/idl_gen_grpc.cpp
- src/idl_gen_grpc.cpp

View File

@@ -27,7 +27,7 @@ jobs:
cxx: [g++-10, clang++-12]
fail-fast: false
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: cmake
run: CXX=${{ matrix.cxx }} cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON .
- name: build
@@ -62,6 +62,16 @@ jobs:
if: matrix.cxx == 'g++-10' && startsWith(github.ref, 'refs/tags/')
id: hash-gcc
run: echo "::set-output name=hashes::$(sha256sum Linux.flatc.binary.${{ matrix.cxx }}.zip | base64 -w0)"
build-linux-no-file-tests:
name: Build Linux with -DFLATBUFFERS_NO_FILE_TESTS
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: cmake
run: CXX=clang++-12 cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON -DFLATBUFFERS_CXX_FLAGS="-DFLATBUFFERS_NO_FILE_TESTS" .
- name: build
run: make -j
build-linux-cpp-std:
name: Build Linux C++
@@ -76,16 +86,20 @@ jobs:
- cxx: g++-10
std: 23
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- 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-windows-cpp-std:
name: Build Windows C++
@@ -95,7 +109,7 @@ jobs:
std: [11, 14, 17, 20, 23]
fail-fast: false
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Add msbuild to PATH
uses: microsoft/setup-msbuild@v1.1
- name: cmake
@@ -103,10 +117,14 @@ jobs:
cmake -G "Visual Studio 16 2019" -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:
permissions:
@@ -116,7 +134,7 @@ jobs:
name: Build Windows 2019
runs-on: windows-2019
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Add msbuild to PATH
uses: microsoft/setup-msbuild@v1.1
- name: cmake
@@ -151,7 +169,7 @@ jobs:
name: Build Windows 2017
runs-on: windows-2019
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Add msbuild to PATH
uses: microsoft/setup-msbuild@v1.1
- name: cmake
@@ -165,7 +183,7 @@ jobs:
name: Build Windows 2015
runs-on: windows-2019
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Add msbuild to PATH
uses: microsoft/setup-msbuild@v1.1
- name: cmake
@@ -187,9 +205,9 @@ jobs:
#'-p:EnableSpanT=true,UnsafeByteBuffer=true'
]
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Setup .NET Core SDK
uses: actions/setup-dotnet@v1.9.0
uses: actions/setup-dotnet@v3
with:
dotnet-version: '3.1.x'
- name: Build
@@ -211,34 +229,33 @@ jobs:
name: Build Mac (for Intel)
runs-on: macos-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: cmake
run: cmake -G "Xcode" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_FLATC_EXECUTABLE=_build/Release/flatc -DFLATBUFFERS_STRICT_MODE=ON .
run: cmake -G "Xcode" -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
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 "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: flatc tests
run: python3 tests/flatc/main.py --flatc ./_build/Release/flatc
run: python3 tests/flatc/main.py --flatc Release/flatc
- name: upload build artifacts
uses: actions/upload-artifact@v1
with:
name: Mac flatc binary
path: _build/Release/flatc
path: Release/flatc
# Below if only for release.
- name: Zip file
if: startsWith(github.ref, 'refs/tags/')
run: mv _build/Release/flatc . && zip MacIntel.flatc.binary.zip flatc
run: mv Release/flatc . && zip MacIntel.flatc.binary.zip flatc
- name: Release binary
uses: softprops/action-gh-release@v1
if: startsWith(github.ref, 'refs/tags/')
@@ -257,32 +274,31 @@ jobs:
name: Build Mac (universal build)
runs-on: macos-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: cmake
run: cmake -G "Xcode" -DCMAKE_OSX_ARCHITECTURES="arm64;x86_64" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_FLATC_EXECUTABLE=_build/Release/flatc -DFLATBUFFERS_STRICT_MODE=ON .
run: cmake -G "Xcode" -DCMAKE_OSX_ARCHITECTURES="arm64;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
run: xcodebuild -toolchain clang -configuration Release -target flattests
- name: check that the binary is "universal"
run: |
info=$(file _build/Release/flatc)
info=$(file Release/flatc)
echo $info
echo $info | grep "Mach-O universal binary with 2 architectures"
- 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
with:
name: Mac flatc binary
path: _build/Release/flatc
path: Release/flatc
# Below if only for release.
- name: Zip file
if: startsWith(github.ref, 'refs/tags/')
run: mv _build/Release/flatc . && zip Mac.flatc.binary.zip flatc
run: mv Release/flatc . && zip Mac.flatc.binary.zip flatc
- name: Release binary
uses: softprops/action-gh-release@v1
if: startsWith(github.ref, 'refs/tags/')
@@ -297,11 +313,12 @@ jobs:
name: Build Android (on Linux)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: set up JDK 1.8
uses: actions/setup-java@v1
- uses: actions/checkout@v3
- name: set up Java
uses: actions/setup-java@v3
with:
java-version: 1.8
distribution: 'temurin'
java-version: '11'
- name: set up flatc
run: |
cmake -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF -DFLATBUFFERS_STRICT_MODE=ON .
@@ -318,7 +335,7 @@ jobs:
matrix:
cxx: [g++-10, clang++-12]
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: cmake
run: CXX=${{ matrix.cxx }} cmake -G "Unix Makefiles" -DFLATBUFFERS_BUILD_TESTS=OFF -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON . && make -j
- name: Generate
@@ -326,6 +343,22 @@ jobs:
- name: Generate gRPC
run: scripts/check-grpc-generated-code.py
build-generator-windows:
name: Check Generated Code on Windows
runs-on: windows-2019
steps:
- uses: actions/checkout@v3
- 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 -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
@@ -333,7 +366,7 @@ jobs:
matrix:
cxx: [g++-10]
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- 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 -DFLATBUFFERS_STRICT_MODE=ON . && make -j
- name: Run benchmarks
@@ -348,21 +381,21 @@ jobs:
name: Build Java
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- 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
steps:
- name: Checkout
uses: actions/checkout@v2
- uses: gradle/wrapper-validation-action@v1
- uses: actions/setup-java@v2
uses: actions/checkout@v3
- uses: gradle/wrapper-validation-action@v1.0.5
- uses: actions/setup-java@v3
with:
distribution: 'adopt-hotspot'
distribution: 'temurin'
java-version: '11'
- name: Build
working-directory: kotlin
@@ -373,16 +406,16 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- uses: actions/setup-java@v2
uses: actions/checkout@v3
- uses: actions/setup-java@v3
with:
distribution: 'adopt-hotspot'
distribution: 'temurin'
java-version: '11'
- uses: gradle/wrapper-validation-action@v1
- uses: gradle/wrapper-validation-action@v1.0.5
- name: Build
working-directory: kotlin
# we are using docker's version of gradle
# so no need for wrapper validadation or user
# so no need for wrapper validation or user
# gradlew
run: gradle jvmMainClasses jvmTest jsTest jsBrowserTest
@@ -390,7 +423,7 @@ jobs:
name: Build Rust
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: test
working-directory: tests
run: bash RustTest.sh
@@ -399,7 +432,7 @@ jobs:
name: Build Python
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: test
working-directory: tests
run: bash PythonTest.sh
@@ -408,7 +441,7 @@ jobs:
name: Build Go
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: flatc
# FIXME: make test script not rely on flatc
run: cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_INSTALL=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF -DFLATBUFFERS_STRICT_MODE=ON . && make -j
@@ -416,14 +449,30 @@ jobs:
working-directory: tests
run: bash GoTest.sh
build-php:
name: Build PHP
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: flatc
# FIXME: make test script not rely on flatc
run: cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_INSTALL=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF -DFLATBUFFERS_STRICT_MODE=ON . && make -j
- name: test
working-directory: tests
run: |
php phpTest.php
sh phpUnionVectorTest.sh
build-swift:
name: Build Swift
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: test
working-directory: tests/FlatBuffers.Test.Swift
run: sh SwiftTest.sh
working-directory: tests/swift/tests
run: |
swift build --build-tests
swift test
build-swift-wasm:
name: Build Swift Wasm
@@ -431,18 +480,18 @@ jobs:
container:
image: ghcr.io/swiftwasm/carton:0.15.3
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Setup Wasmer
uses: wasmerio/setup-wasmer@v1
uses: wasmerio/setup-wasmer@v2
- name: Test
working-directory: tests/FlatBuffers.Test.Swift.Wasm
working-directory: tests/swift/Wasm.tests
run: carton test
build-ts:
name: Build TS
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: flatc
# FIXME: make test script not rely on flatc
run: cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_INSTALL=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF . && make -j
@@ -451,14 +500,14 @@ jobs:
- name: compile
run: yarn compile
- name: test
working-directory: tests
working-directory: tests/ts
run: python3 TypeScriptTest.py
build-dart:
name: Build Dart
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: dart-lang/setup-dart@v1
with:
sdk: stable
@@ -469,6 +518,22 @@ jobs:
working-directory: tests
run: bash DartTest.sh
build-nim:
name: Build Nim
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: flatc
# FIXME: make test script not rely on flatc
run: cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_INSTALL=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF . && make -j
- uses: jiro4989/setup-nim-action@v1
- name: install library
working-directory: nim
run: nimble -y develop
- name: test
working-directory: tests/nim
run: python3 testnim.py
release-digests:
if: startsWith(github.ref, 'refs/tags/')
needs: [build-linux, build-windows, build-mac-intel, build-mac-universal]
@@ -500,7 +565,8 @@ jobs:
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@v1.2.0
uses: slsa-framework/slsa-github-generator/.github/workflows/generator_generic_slsa3.yml@v1.2.1
with:
base64-subjects: "${{ needs.release-digests.outputs.digests }}"
upload-assets: true # Optional: Upload to a new release
compile-generator: true # Workaround for https://github.com/slsa-framework/slsa-github-generator/issues/1163

35
.github/workflows/extrabuild.yml vendored Normal file
View File

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

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

@@ -0,0 +1,106 @@
name: Release
permissions: read-all
on:
# For manual tests.
workflow_dispatch:
release:
types: [created]
jobs:
publish-npm:
name: Publish NPM
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '16.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@v3
- uses: actions/setup-python@v4
with:
python-version: '3.10'
- name: Install Dependencies
run: |
python3 -m pip install --upgrade pip
python3 -m pip install setuptools wheel twine
- name: Build
run: |
python3 setup.py sdist bdist_wheel
- 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@v3
- uses: actions/setup-dotnet@v3
with:
dotnet-version: '6.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@v3
- name: Set up Maven Central Repository
uses: actions/setup-java@v3
with:
java-version: '11'
distribution: 'adopt'
cache: 'maven'
server-id: ossrh
server-username: OSSRH_USERNAME
server-password: OSSRH_PASSWORD
gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }}
gpg-passphrase: MAVEN_GPG_PASSPHRASE # this needs to be an env var
- name: Publish Maven
run: mvn --batch-mode clean deploy
env:
OSSRH_USERNAME: ${{ secrets.OSSRH_USERNAME }}
OSSRH_PASSWORD: ${{ secrets.OSSRH_TOKEN }}
MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }}

6
.gitignore vendored
View File

@@ -78,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/**
@@ -88,6 +88,7 @@ java/*.iml
.idea
*.iml
target
java/target
**/*.pyc
build/VS2010/FlatBuffers.sdf
build/VS2010/FlatBuffers.opensdf
@@ -148,4 +149,5 @@ flatbuffers.pc
**/html/**
**/latex/**
# https://cmake.org/cmake/help/latest/module/FetchContent.html#variable:FETCHCONTENT_BASE_DIR
_deps/
cmake-build-debug/
_deps/

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

@@ -44,6 +44,7 @@ filegroup(
"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",

View File

@@ -4,33 +4,89 @@ All major or breaking changes will be documented in this file, as well as any
new features that should be highlighted. Minor fixes or improvements are not
necessarily listed.
## [23.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](https://github.com/google/flatbuffers/issues/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.
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.
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).
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.
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.
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.
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.
* 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

@@ -438,14 +438,12 @@ 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}")
# 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_MAJOR}"
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)
@@ -654,9 +652,9 @@ 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_CURRENT_BINARY_DIR}/flatbuffers-config-version.cmake"
DESTINATION ${FB_CMAKE_DIR}
)

View File

@@ -1,37 +1,39 @@
set(VERSION_MAJOR 2)
set(VERSION_MINOR 0)
set(VERSION_PATCH 8)
set(VERSION_MAJOR 23)
set(VERSION_MINOR 1)
set(VERSION_PATCH 20)
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)
# 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)
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_DIRTY}\" does not match pattern v<major>.<minor>.<patch>-<commit>")
message(WARNING "git describe failed with exit code: ${GIT_DESCRIBE_RESULT}")
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

@@ -71,10 +71,10 @@ 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_STRICT_MODE
option(FLATBUFFERS_STRICT_MODE
"Build flatbuffers with all warnings as errors (-Werror or /WX)."
OFF)
@@ -125,6 +125,13 @@ if(NOT DEFINED FLATBUFFERS_LOCALE_INDEPENDENT)
endif()
add_definitions(-DFLATBUFFERS_LOCALE_INDEPENDENT=$<BOOL:${FLATBUFFERS_LOCALE_INDEPENDENT}>)
if(NOT WIN32)
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
@@ -134,6 +141,7 @@ set(FlatBuffers_Library_SRCS
include/flatbuffers/buffer_ref.h
include/flatbuffers/default_allocator.h
include/flatbuffers/detached_buffer.h
include/flatbuffers/code_generator.h
include/flatbuffers/flatbuffer_builder.h
include/flatbuffers/flatbuffers.h
include/flatbuffers/flexbuffers.h
@@ -182,6 +190,7 @@ set(FlatBuffers_Compiler_SRCS
src/flatc_main.cpp
src/bfbs_gen.h
src/bfbs_gen_lua.h
src/bfbs_gen_nim.h
src/bfbs_namer.h
include/flatbuffers/code_generators.h
src/binary_annotator.h
@@ -189,6 +198,7 @@ set(FlatBuffers_Compiler_SRCS
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
@@ -217,6 +227,7 @@ set(FlatBuffers_Tests_SRCS
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
@@ -230,6 +241,8 @@ set(FlatBuffers_Tests_SRCS
tests/util_test.cpp
tests/native_type_test_impl.h
tests/native_type_test_impl.cpp
tests/alignment_test.h
tests/alignment_test.cpp
include/flatbuffers/code_generators.h
src/code_generators.cpp
# file generate by running compiler on tests/monster_test.fbs
@@ -251,6 +264,10 @@ set(FlatBuffers_Tests_SRCS
${CMAKE_CURRENT_BINARY_DIR}/tests/optional_scalars_generated.h
# file generate by running compiler on tests/native_inline_table_test.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/native_inline_table_test_generated.h
# file generate by running compiler on tests/alignment_test.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/alignment_test_generated.h
# file generate by running compiler on tests/key_field/key_field_sample.fbs
${CMAKE_CURRENT_BINARY_DIR}/tests/key_field/key_field_sample_generated.h
)
set(FlatBuffers_Tests_CPP17_SRCS
@@ -352,8 +369,8 @@ 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
# 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
@@ -369,7 +386,7 @@ set(CMAKE_CXX_EXTENSIONS OFF)
if(MSVC_LIKE)
target_compile_options(ProjectConfig
INTERFACE
INTERFACE
/W4
$<$<BOOL:${FLATBUFFERS_STRICT_MODE}>:
/WX # Treat all compiler warnings as errors
@@ -401,8 +418,8 @@ else()
-Wno-error=stringop-overflow
>
>
-pedantic
-Wextra
-pedantic
-Wextra
-Wno-unused-parameter
-Wold-style-cast
-fsigned-char
@@ -410,13 +427,14 @@ else()
# 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}>:
$<$<BOOL:${FLATBUFFERS_STRICT_MODE}>:
-Werror=unused-private-field
>
>
@@ -425,7 +443,7 @@ else()
$<$<CXX_COMPILER_ID:GNU>:
$<$<VERSION_GREATER:$<CXX_COMPILER_VERSION>,4.4>:
-Wunused-result
-Wunused-parameter
-Wunused-parameter
-Werror=unused-parameter
-Wmissing-declarations
>
@@ -433,7 +451,7 @@ else()
-Wzero-as-null-pointer-constant
>
$<$<VERSION_GREATER:$<CXX_COMPILER_VERSION>,7.0>:
-faligned-new
-faligned-new
$<$<BOOL:${FLATBUFFERS_STRICT_MODE}>:
-Werror=implicit-fallthrough=2
>
@@ -463,7 +481,7 @@ if(FLATBUFFERS_BUILD_FLATLIB)
add_library(flatbuffers STATIC ${FlatBuffers_Library_SRCS})
# Attach header directory for when build via add_subdirectory().
target_include_directories(flatbuffers
target_include_directories(flatbuffers
INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
)
@@ -481,7 +499,7 @@ if(FLATBUFFERS_BUILD_FLATC)
endif()
target_link_libraries(flatc PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
target_compile_options(flatc
target_compile_options(flatc
PUBLIC
$<$<AND:$<BOOL:${MSVC_LIKE}>,$<CONFIG:Release>>:
/MT
@@ -507,14 +525,12 @@ endif()
if(FLATBUFFERS_BUILD_SHAREDLIB)
add_library(flatbuffers_shared SHARED ${FlatBuffers_Library_SRCS})
target_link_libraries(flatbuffers_shared PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
# 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}")
# 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_MAJOR}"
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)
@@ -572,7 +588,7 @@ function(compile_flatbuffers_schema_to_binary SRC_FBS)
OUTPUT ${GEN_BINARY_SCHEMA}
COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}"
-b --schema --bfbs-comments --bfbs-builtins
--bfbs-filenames ${SRC_FBS_DIR}
--bfbs-filenames "${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS_DIR}"
-I "${CMAKE_CURRENT_SOURCE_DIR}/tests/include_test"
-o "${SRC_FBS_DIR}"
"${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}"
@@ -616,13 +632,15 @@ if(FLATBUFFERS_BUILD_TESTS)
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_opt(tests/union_vector/union_vector.fbs "--no-includes;--gen-compare;")
compile_flatbuffers_schema_to_cpp(tests/optional_scalars.fbs)
compile_flatbuffers_schema_to_cpp_opt(tests/native_type_test.fbs "")
compile_flatbuffers_schema_to_cpp_opt(tests/arrays_test.fbs "--scoped-enums;--gen-compare")
compile_flatbuffers_schema_to_binary(tests/arrays_test.fbs)
compile_flatbuffers_schema_to_embedded_binary(tests/monster_test.fbs "--no-includes;--gen-compare")
compile_flatbuffers_schema_to_cpp(tests/native_inline_table_test.fbs "--gen-compare")
compile_flatbuffers_schema_to_cpp(tests/alignment_test.fbs "--gen-compare")
compile_flatbuffers_schema_to_cpp(tests/key_field/key_field_sample.fbs)
if(NOT (MSVC AND (MSVC_VERSION LESS 1900)))
compile_flatbuffers_schema_to_cpp(tests/monster_extra.fbs) # Test floating-point NAN/INF.
endif()
@@ -682,13 +700,13 @@ if(FLATBUFFERS_BUILD_GRPCTEST)
find_package(gRPC CONFIG REQUIRED)
add_executable(grpctest ${FlatBuffers_GRPCTest_SRCS})
add_dependencies(grpctest generated_code)
target_link_libraries(grpctext
PRIVATE
target_link_libraries(grpctext
PRIVATE
$<BUILD_INTERFACE:ProjectConfig>
gRPC::grpc++_unsecure
gRPC::gpr
gRPC::grpc++_unsecure
gRPC::gpr
pthread
dl
dl
)
endif()
@@ -699,9 +717,12 @@ 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}
)

View File

@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'FlatBuffers'
s.version = '2.0.0'
s.version = '23.1.20'
s.summary = 'FlatBuffers: Memory Efficient Serialization Library'
s.description = "FlatBuffers is a cross platform serialization library architected for
@@ -11,11 +11,11 @@ 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.source = { :git => 'https://github.com/google/flatbuffers.git', :tag => 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.source_files = 'swift/Sources/Flatbuffers/*.swift'
end

View File

@@ -32,5 +32,6 @@ let package = Package(
.target(
name: "FlatBuffers",
dependencies: [],
path: "swift/Sources",
exclude: ["Documentation.docc/Resources/code/swift"]),
])

View File

@@ -31,6 +31,7 @@ let package = Package(
targets: [
.target(
name: "FlatBuffers",
dependencies: []),
dependencies: [],
path: "swift/Sources"),
])

View File

@@ -33,10 +33,10 @@ swift_rules_extra_dependencies()
http_archive(
name = "io_bazel_rules_go",
sha256 = "16e9fca53ed6bd4ff4ad76facc9b7b651a89db1689a2877d6fd7b82aa824e366",
sha256 = "ae013bf35bd23234d1dea46b079f1e05ba74ac0321423830119d3e787ec73483",
urls = [
"https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.34.0/rules_go-v0.34.0.zip",
"https://github.com/bazelbuild/rules_go/releases/download/v0.34.0/rules_go-v0.34.0.zip",
"https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.36.0/rules_go-v0.36.0.zip",
"https://github.com/bazelbuild/rules_go/releases/download/v0.36.0/rules_go-v0.36.0.zip",
],
)
@@ -56,10 +56,13 @@ http_archive(
)
##### GRPC
_GRPC_VERSION = "1.48.0" # https://github.com/grpc/grpc/releases/tag/v1.48.0
_GRPC_VERSION = "1.49.0" # https://github.com/grpc/grpc/releases/tag/v1.48.0
http_archive(
name = "com_github_grpc_grpc",
patch_args = ["-p1"],
patches = ["//grpc:build_grpc_with_cxx14.patch"],
sha256 = "15715e1847cc9e42014f02c727dbcb48e39dbdb90f79ad3d66fe4361709ff935",
strip_prefix = "grpc-" + _GRPC_VERSION,
urls = ["https://github.com/grpc/grpc/archive/refs/tags/v" + _GRPC_VERSION + ".tar.gz"],
)

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

@@ -8,7 +8,7 @@ android {
defaultConfig {
applicationId "com.flatbuffers.app"
minSdkVersion 16
minSdkVersion 26
targetSdkVersion 30
versionCode 1
versionName "1.0"
@@ -18,6 +18,14 @@ android {
targetCompatibility JavaVersion.VERSION_1_8
}
sourceSets {
main {
java {
srcDir '../../java/src/main/java/'
}
}
}
ndk {
abiFilters 'arm64-v8a', 'armeabi-v7a'
}
@@ -105,30 +113,6 @@ android {
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"
// }
// }
// }
// }
}
dependencies {
@@ -136,6 +120,8 @@ dependencies {
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'
// If you using java runtime you can add its dependency as the example below
// implementation 'com.google.flatbuffers:flatbuffers-java:$latest_version'
}

View File

@@ -6,6 +6,13 @@
#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 == 2 &&
FLATBUFFERS_VERSION_MINOR == 0 &&
FLATBUFFERS_VERSION_REVISION == 8,
"Non-compatible flatbuffers version included");
namespace com {
namespace fbs {
namespace app {

View File

@@ -2,9 +2,21 @@
package com.fbs.app
import java.nio.*
import com.google.flatbuffers.BaseVector
import com.google.flatbuffers.BooleanVector
import com.google.flatbuffers.ByteVector
import com.google.flatbuffers.Constants
import com.google.flatbuffers.DoubleVector
import com.google.flatbuffers.FlatBufferBuilder
import com.google.flatbuffers.FloatVector
import com.google.flatbuffers.LongVector
import com.google.flatbuffers.StringVector
import com.google.flatbuffers.Struct
import com.google.flatbuffers.Table
import com.google.flatbuffers.UnionVector
import java.nio.ByteBuffer
import java.nio.ByteOrder
import kotlin.math.sign
import com.google.flatbuffers.*
@Suppress("unused")
class Animal : Table() {
@@ -36,7 +48,7 @@ class Animal : Table() {
return if(o != 0) bb.getShort(o + bb_pos).toUShort() else 0u
}
companion object {
fun validateVersion() = Constants.FLATBUFFERS_2_0_0()
fun validateVersion() = Constants.FLATBUFFERS_23_1_20()
fun getRootAsAnimal(_bb: ByteBuffer): Animal = getRootAsAnimal(_bb, Animal())
fun getRootAsAnimal(_bb: ByteBuffer, obj: Animal): Animal {
_bb.order(ByteOrder.LITTLE_ENDIAN)

View File

@@ -27,7 +27,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)

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

@@ -21,14 +21,6 @@ def get_branch():
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)

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

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

View File

@@ -1,5 +1,5 @@
name: flat_buffers
version: 2.0.8
version: 23.1.20
description: FlatBuffers reading and writing library for Dart. Based on original work by Konstantin Scheglov and Paul Berry of the Dart SDK team.
homepage: https://github.com/google/flatbuffers
documentation: https://google.github.io/flatbuffers/index.html

View File

@@ -0,0 +1,207 @@
// automatically generated by the FlatBuffers compiler, do not modify
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
import 'dart:typed_data' show Uint8List;
import 'package:flat_buffers/flat_buffers.dart' as fb;
class 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;
}
}

View File

@@ -87,7 +87,10 @@ class CheckOtherLangaugesData {
'testrequirednestedflatbuffer: null, scalarKeySortedTables: null, '
'nativeInline: null, '
'longEnumNonEnumDefault: LongEnum{value: 0}, '
'longEnumNormalDefault: LongEnum{value: 2}}, '
'longEnumNormalDefault: LongEnum{value: 2}, 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, '
@@ -110,7 +113,10 @@ class CheckOtherLangaugesData {
'testrequirednestedflatbuffer: null, scalarKeySortedTables: null, '
'nativeInline: null, '
'longEnumNonEnumDefault: LongEnum{value: 0}, '
'longEnumNormalDefault: LongEnum{value: 2}}, '
'longEnumNormalDefault: LongEnum{value: 2}, 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, '
@@ -137,7 +143,10 @@ class CheckOtherLangaugesData {
'miss, val: 0, count: 0}, Stat{id: hit, val: 10, count: 1}], '
'nativeInline: Test{a: 1, b: 2}, '
'longEnumNonEnumDefault: LongEnum{value: 0}, '
'longEnumNormalDefault: LongEnum{value: 2}}',
'longEnumNormalDefault: LongEnum{value: 2}, nanDefault: NaN, '
'infDefault: Infinity, positiveInfDefault: Infinity, infinityDefault: '
'Infinity, positiveInfinityDefault: Infinity, negativeInfDefault: '
'-Infinity, negativeInfinityDefault: -Infinity, doubleInfDefault: Infinity}'
);
}
}

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

View File

@@ -37,6 +37,7 @@ void main() {
// expect(FlxValue.fromBuffer(b([255, 255, 255, 255, 255, 255, 255, 255, 11, 8])).intValue, 18446744073709551615);
});
test('double value', () {
expect(Reference.fromBuffer(b([0, 0, 128, 63, 14, 4])).doubleValue, 1.0);
expect(Reference.fromBuffer(b([0, 0, 144, 64, 14, 4])).doubleValue, 4.5);
expect(Reference.fromBuffer(b([205, 204, 204, 61, 14, 4])).doubleValue,
closeTo(.1, .001));

View File

@@ -0,0 +1,109 @@
// automatically generated by the FlatBuffers compiler, do not modify
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
import 'dart:typed_data' show Uint8List;
import 'package:flat_buffers/flat_buffers.dart' as fb;
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,241 @@
// automatically generated by the FlatBuffers compiler, do not modify
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
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';
class FromInclude {
final int value;
const FromInclude._(this.value);
factory FromInclude.fromValue(int value) {
final result = values[value];
if (result == null) {
throw StateError('Invalid value $value for bit flag enum FromInclude');
}
return result;
}
static FromInclude? _createOrNull(int? value) =>
value == null ? null : FromInclude.fromValue(value);
static const int minValue = 0;
static const int maxValue = 0;
static bool containsValue(int value) => values.containsKey(value);
static const FromInclude IncludeVal = FromInclude._(0);
static const Map<int, FromInclude> values = {
0: IncludeVal};
static const fb.Reader<FromInclude> reader = _FromIncludeReader();
@override
String toString() {
return 'FromInclude{value: $value}';
}
}
class _FromIncludeReader extends fb.Reader<FromInclude> {
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;
}
}

View File

@@ -278,3 +278,122 @@ class KeywordsInTableObjectBuilder extends fb.ObjectBuilder {
return fbBuilder.buffer;
}
}
class Table2 {
Table2._(this._bc, this._bcOffset);
factory Table2(List<int> bytes) {
final rootRef = fb.BufferContext.fromBytes(bytes);
return reader.read(rootRef, 0);
}
static const fb.Reader<Table2> reader = _Table2Reader();
final fb.BufferContext _bc;
final int _bcOffset;
KeywordsInUnionTypeId? get typeType => KeywordsInUnionTypeId._createOrNull(const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 4));
dynamic get type {
switch (typeType?.value) {
case 1: return KeywordsInTable.reader.vTableGetNullable(_bc, _bcOffset, 6);
case 2: return KeywordsInTable.reader.vTableGetNullable(_bc, _bcOffset, 6);
default: return null;
}
}
@override
String toString() {
return 'Table2{typeType: ${typeType}, type: ${type}}';
}
Table2T unpack() => Table2T(
typeType: typeType,
type: type);
static int pack(fb.Builder fbBuilder, Table2T? object) {
if (object == null) return 0;
return object.pack(fbBuilder);
}
}
class Table2T implements fb.Packable {
KeywordsInUnionTypeId? typeType;
dynamic type;
Table2T({
this.typeType,
this.type});
@override
int pack(fb.Builder fbBuilder) {
final int? typeOffset = type?.pack(fbBuilder);
fbBuilder.startTable(2);
fbBuilder.addUint8(0, typeType?.value);
fbBuilder.addOffset(1, typeOffset);
return fbBuilder.endTable();
}
@override
String toString() {
return 'Table2T{typeType: ${typeType}, type: ${type}}';
}
}
class _Table2Reader extends fb.TableReader<Table2> {
const _Table2Reader();
@override
Table2 createObject(fb.BufferContext bc, int offset) =>
Table2._(bc, offset);
}
class Table2Builder {
Table2Builder(this.fbBuilder);
final fb.Builder fbBuilder;
void begin() {
fbBuilder.startTable(2);
}
int addTypeType(KeywordsInUnionTypeId? typeType) {
fbBuilder.addUint8(0, typeType?.value);
return fbBuilder.offset;
}
int addTypeOffset(int? offset) {
fbBuilder.addOffset(1, offset);
return fbBuilder.offset;
}
int finish() {
return fbBuilder.endTable();
}
}
class Table2ObjectBuilder extends fb.ObjectBuilder {
final KeywordsInUnionTypeId? _typeType;
final dynamic _type;
Table2ObjectBuilder({
KeywordsInUnionTypeId? typeType,
dynamic type,
})
: _typeType = typeType,
_type = type;
/// Finish building, and store into the [fbBuilder].
@override
int finish(fb.Builder fbBuilder) {
final int? typeOffset = _type?.getOrCreateOffset(fbBuilder);
fbBuilder.startTable(2);
fbBuilder.addUint8(0, _typeType?.value);
fbBuilder.addOffset(1, typeOffset);
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,155 @@
// automatically generated by the FlatBuffers compiler, do not modify
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
import 'dart:typed_data' show Uint8List;
import 'package:flat_buffers/flat_buffers.dart' as fb;
class OptionsEnum {
final int value;
const OptionsEnum._(this.value);
factory OptionsEnum.fromValue(int value) {
final result = values[value];
if (result == null) {
throw StateError('Invalid value $value for bit flag enum OptionsEnum');
}
return result;
}
static OptionsEnum? _createOrNull(int? value) =>
value == null ? null : OptionsEnum.fromValue(value);
static const int minValue = 1;
static const int maxValue = 3;
static bool containsValue(int value) => values.containsKey(value);
static const OptionsEnum A = OptionsEnum._(1);
static const OptionsEnum B = OptionsEnum._(2);
static const OptionsEnum C = OptionsEnum._(3);
static const Map<int, OptionsEnum> values = {
1: A,
2: B,
3: C};
static const fb.Reader<OptionsEnum> reader = _OptionsEnumReader();
@override
String toString() {
return 'OptionsEnum{value: $value}';
}
}
class _OptionsEnumReader extends fb.Reader<OptionsEnum> {
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

@@ -31,6 +31,14 @@ enum Race:byte {
Elf,
}
enum LongEnum:ulong (bit_flags) {
LongOne = 1,
LongTwo = 2,
// Because this is a bitflag, 40 will be out of range of a 32-bit integer,
// allowing us to exercise any logic special to big numbers.
LongBig = 40,
}
union Any { Monster, TestSimpleTableWithEnum, MyGame.Example2.Monster }
union AnyUniqueAliases { M: Monster, TS: TestSimpleTableWithEnum, M2: MyGame.Example2.Monster }
@@ -62,6 +70,10 @@ struct StructOfStructs {
c: Ability;
}
struct StructOfStructsOfStructs {
a: StructOfStructs;
}
table Stat {
id:string;
val:long;
@@ -124,6 +136,20 @@ table Monster {
signed_enum:Race = None (id:48);
testrequirednestedflatbuffer:[ubyte] (id:49, nested_flatbuffer: "Monster");
scalar_key_sorted_tables:[Stat] (id: 50);
native_inline:Test (id: 51, native_inline);
// The default value of this enum will be a numeric zero, which isn't a valid
// enum value.
long_enum_non_enum_default:LongEnum (id: 52);
long_enum_normal_default:LongEnum = LongOne (id: 53);
// Test that default values nan and +/-inf work.
nan_default:float = nan (id: 54);
inf_default:float = inf (id: 55);
positive_inf_default:float = +inf (id: 56);
infinity_default:float = infinity (id: 57);
positive_infinity_default:float = +infinity (id: 58);
negative_inf_default:float = -inf (id: 59);
negative_infinity_default:float = -infinity (id: 60);
double_inf_default:double = inf (id: 61);
}
table TypeAliases {

View File

@@ -9,6 +9,8 @@ import 'package:flat_buffers/flat_buffers.dart' as fb;
import './monster_test_my_game_generated.dart' as my_game;
import './monster_test_my_game.example_generated.dart' as my_game_example;
import './include_test1_generated.dart';
class Monster {
Monster._(this._bc, this._bcOffset);
factory Monster(List<int> bytes) {

View File

@@ -9,6 +9,8 @@ import 'package:flat_buffers/flat_buffers.dart' as fb;
import './monster_test_my_game_generated.dart' as my_game;
import './monster_test_my_game.example2_generated.dart' as my_game_example2;
import './include_test1_generated.dart';
/// Composite components of Monster color.
class Color {
final int value;
@@ -17,7 +19,11 @@ class Color {
factory Color.fromValue(int value) {
final result = values[value];
if (result == null) {
throw StateError('Invalid value $value for bit flag enum Color');
if (value == 0) {
return Color._(0);
} else {
throw StateError('Invalid value $value for bit flag enum Color');
}
}
return result;
}
@@ -66,7 +72,7 @@ class Race {
factory Race.fromValue(int value) {
final result = values[value];
if (result == null) {
throw StateError('Invalid value $value for bit flag enum Race');
throw StateError('Invalid value $value for bit flag enum Race');
}
return result;
}
@@ -107,6 +113,54 @@ class _RaceReader extends fb.Reader<Race> {
Race.fromValue(const fb.Int8Reader().read(bc, offset));
}
class LongEnum {
final int value;
const LongEnum._(this.value);
factory LongEnum.fromValue(int value) {
final result = values[value];
if (result == null) {
if (value == 0) {
return LongEnum._(0);
} else {
throw StateError('Invalid value $value for bit flag enum LongEnum');
}
}
return result;
}
static LongEnum? _createOrNull(int? value) =>
value == null ? null : LongEnum.fromValue(value);
static bool containsValue(int value) => values.containsKey(value);
static const LongEnum LongOne = LongEnum._(2);
static const LongEnum LongTwo = LongEnum._(4);
static const LongEnum LongBig = LongEnum._(1099511627776);
static const Map<int, LongEnum> values = {
2: LongOne,
4: LongTwo,
1099511627776: LongBig};
static const fb.Reader<LongEnum> reader = _LongEnumReader();
@override
String toString() {
return 'LongEnum{value: $value}';
}
}
class _LongEnumReader extends fb.Reader<LongEnum> {
const _LongEnumReader();
@override
int get size => 8;
@override
LongEnum read(fb.BufferContext bc, int offset) =>
LongEnum.fromValue(const fb.Uint64Reader().read(bc, offset));
}
class AnyTypeId {
final int value;
const AnyTypeId._(this.value);
@@ -114,7 +168,7 @@ class AnyTypeId {
factory AnyTypeId.fromValue(int value) {
final result = values[value];
if (result == null) {
throw StateError('Invalid value $value for bit flag enum AnyTypeId');
throw StateError('Invalid value $value for bit flag enum AnyTypeId');
}
return result;
}
@@ -162,7 +216,7 @@ class AnyUniqueAliasesTypeId {
factory AnyUniqueAliasesTypeId.fromValue(int value) {
final result = values[value];
if (result == null) {
throw StateError('Invalid value $value for bit flag enum AnyUniqueAliasesTypeId');
throw StateError('Invalid value $value for bit flag enum AnyUniqueAliasesTypeId');
}
return result;
}
@@ -210,7 +264,7 @@ class AnyAmbiguousAliasesTypeId {
factory AnyAmbiguousAliasesTypeId.fromValue(int value) {
final result = values[value];
if (result == null) {
throw StateError('Invalid value $value for bit flag enum AnyAmbiguousAliasesTypeId');
throw StateError('Invalid value $value for bit flag enum AnyAmbiguousAliasesTypeId');
}
return result;
}
@@ -264,7 +318,7 @@ class Test {
@override
String toString() {
return 'Test{a: $a, b: $b}';
return 'Test{a: ${a}, b: ${b}}';
}
TestT unpack() => TestT(
@@ -295,7 +349,7 @@ class TestT implements fb.Packable {
@override
String toString() {
return 'TestT{a: $a, b: $b}';
return 'TestT{a: ${a}, b: ${b}}';
}
}
@@ -368,7 +422,7 @@ class TestSimpleTableWithEnum {
@override
String toString() {
return 'TestSimpleTableWithEnum{color: $color}';
return 'TestSimpleTableWithEnum{color: ${color}}';
}
TestSimpleTableWithEnumT unpack() => TestSimpleTableWithEnumT(
@@ -395,7 +449,7 @@ class TestSimpleTableWithEnumT implements fb.Packable {
@override
String toString() {
return 'TestSimpleTableWithEnumT{color: $color}';
return 'TestSimpleTableWithEnumT{color: ${color}}';
}
}
@@ -467,7 +521,7 @@ class Vec3 {
@override
String toString() {
return 'Vec3{x: $x, y: $y, z: $z, test1: $test1, test2: $test2, test3: $test3}';
return 'Vec3{x: ${x}, y: ${y}, z: ${z}, test1: ${test1}, test2: ${test2}, test3: ${test3}}';
}
Vec3T unpack() => Vec3T(
@@ -516,7 +570,7 @@ class Vec3T implements fb.Packable {
@override
String toString() {
return 'Vec3T{x: $x, y: $y, z: $z, test1: $test1, test2: $test2, test3: $test3}';
return 'Vec3T{x: ${x}, y: ${y}, z: ${z}, test1: ${test1}, test2: ${test2}, test3: ${test3}}';
}
}
@@ -610,7 +664,7 @@ class Ability {
@override
String toString() {
return 'Ability{id: $id, distance: $distance}';
return 'Ability{id: ${id}, distance: ${distance}}';
}
AbilityT unpack() => AbilityT(
@@ -640,7 +694,7 @@ class AbilityT implements fb.Packable {
@override
String toString() {
return 'AbilityT{id: $id, distance: $distance}';
return 'AbilityT{id: ${id}, distance: ${distance}}';
}
}
@@ -709,7 +763,7 @@ class StructOfStructs {
@override
String toString() {
return 'StructOfStructs{a: $a, b: $b, c: $c}';
return 'StructOfStructs{a: ${a}, b: ${b}, c: ${c}}';
}
StructOfStructsT unpack() => StructOfStructsT(
@@ -743,7 +797,7 @@ class StructOfStructsT implements fb.Packable {
@override
String toString() {
return 'StructOfStructsT{a: $a, b: $b, c: $c}';
return 'StructOfStructsT{a: ${a}, b: ${b}, c: ${c}}';
}
}
@@ -803,6 +857,94 @@ class StructOfStructsObjectBuilder extends fb.ObjectBuilder {
return fbBuilder.buffer;
}
}
class StructOfStructsOfStructs {
StructOfStructsOfStructs._(this._bc, this._bcOffset);
static const fb.Reader<StructOfStructsOfStructs> reader = _StructOfStructsOfStructsReader();
final fb.BufferContext _bc;
final int _bcOffset;
StructOfStructs get a => StructOfStructs.reader.read(_bc, _bcOffset + 0);
@override
String toString() {
return 'StructOfStructsOfStructs{a: ${a}}';
}
StructOfStructsOfStructsT unpack() => StructOfStructsOfStructsT(
a: a.unpack());
static int pack(fb.Builder fbBuilder, StructOfStructsOfStructsT? object) {
if (object == null) return 0;
return object.pack(fbBuilder);
}
}
class StructOfStructsOfStructsT implements fb.Packable {
StructOfStructsT a;
StructOfStructsOfStructsT({
required this.a});
@override
int pack(fb.Builder fbBuilder) {
a.pack(fbBuilder);
return fbBuilder.offset;
}
@override
String toString() {
return 'StructOfStructsOfStructsT{a: ${a}}';
}
}
class _StructOfStructsOfStructsReader extends fb.StructReader<StructOfStructsOfStructs> {
const _StructOfStructsOfStructsReader();
@override
int get size => 20;
@override
StructOfStructsOfStructs createObject(fb.BufferContext bc, int offset) =>
StructOfStructsOfStructs._(bc, offset);
}
class StructOfStructsOfStructsBuilder {
StructOfStructsOfStructsBuilder(this.fbBuilder);
final fb.Builder fbBuilder;
int finish(fb.StructBuilder a) {
a();
return fbBuilder.offset;
}
}
class StructOfStructsOfStructsObjectBuilder extends fb.ObjectBuilder {
final StructOfStructsObjectBuilder _a;
StructOfStructsOfStructsObjectBuilder({
required StructOfStructsObjectBuilder a,
})
: _a = a;
/// Finish building, and store into the [fbBuilder].
@override
int finish(fb.Builder fbBuilder) {
_a.finish(fbBuilder);
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 Stat {
Stat._(this._bc, this._bcOffset);
factory Stat(List<int> bytes) {
@@ -821,7 +963,7 @@ class Stat {
@override
String toString() {
return 'Stat{id: $id, val: $val, count: $count}';
return 'Stat{id: ${id}, val: ${val}, count: ${count}}';
}
StatT unpack() => StatT(
@@ -858,7 +1000,7 @@ class StatT implements fb.Packable {
@override
String toString() {
return 'StatT{id: $id, val: $val, count: $count}';
return 'StatT{id: ${id}, val: ${val}, count: ${count}}';
}
}
@@ -947,7 +1089,7 @@ class Referrable {
@override
String toString() {
return 'Referrable{id: $id}';
return 'Referrable{id: ${id}}';
}
ReferrableT unpack() => ReferrableT(
@@ -974,7 +1116,7 @@ class ReferrableT implements fb.Packable {
@override
String toString() {
return 'ReferrableT{id: $id}';
return 'ReferrableT{id: ${id}}';
}
}
@@ -1115,10 +1257,21 @@ class Monster {
Race get signedEnum => Race.fromValue(const fb.Int8Reader().vTableGet(_bc, _bcOffset, 100, -1));
List<int>? get testrequirednestedflatbuffer => const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 102);
List<Stat>? get scalarKeySortedTables => const fb.ListReader<Stat>(Stat.reader).vTableGetNullable(_bc, _bcOffset, 104);
Test? get nativeInline => Test.reader.vTableGetNullable(_bc, _bcOffset, 106);
LongEnum get longEnumNonEnumDefault => LongEnum.fromValue(const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 108, 0));
LongEnum get longEnumNormalDefault => LongEnum.fromValue(const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 110, 2));
double get nanDefault => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 112, double.nan);
double get infDefault => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 114, double.infinity);
double get positiveInfDefault => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 116, double.infinity);
double get infinityDefault => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 118, double.infinity);
double get positiveInfinityDefault => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 120, double.infinity);
double get negativeInfDefault => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 122, double.negativeInfinity);
double get negativeInfinityDefault => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 124, double.negativeInfinity);
double get doubleInfDefault => const fb.Float64Reader().vTableGet(_bc, _bcOffset, 126, double.infinity);
@override
String toString() {
return 'Monster{pos: $pos, mana: $mana, hp: $hp, name: $name, inventory: $inventory, color: $color, testType: $testType, test: $test, test4: $test4, testarrayofstring: $testarrayofstring, testarrayoftables: $testarrayoftables, enemy: $enemy, testnestedflatbuffer: $testnestedflatbuffer, testempty: $testempty, testbool: $testbool, testhashs32Fnv1: $testhashs32Fnv1, testhashu32Fnv1: $testhashu32Fnv1, testhashs64Fnv1: $testhashs64Fnv1, testhashu64Fnv1: $testhashu64Fnv1, testhashs32Fnv1a: $testhashs32Fnv1a, testhashu32Fnv1a: $testhashu32Fnv1a, testhashs64Fnv1a: $testhashs64Fnv1a, testhashu64Fnv1a: $testhashu64Fnv1a, testarrayofbools: $testarrayofbools, testf: $testf, testf2: $testf2, testf3: $testf3, testarrayofstring2: $testarrayofstring2, testarrayofsortedstruct: $testarrayofsortedstruct, flex: $flex, test5: $test5, vectorOfLongs: $vectorOfLongs, vectorOfDoubles: $vectorOfDoubles, parentNamespaceTest: $parentNamespaceTest, vectorOfReferrables: $vectorOfReferrables, singleWeakReference: $singleWeakReference, vectorOfWeakReferences: $vectorOfWeakReferences, vectorOfStrongReferrables: $vectorOfStrongReferrables, coOwningReference: $coOwningReference, vectorOfCoOwningReferences: $vectorOfCoOwningReferences, nonOwningReference: $nonOwningReference, vectorOfNonOwningReferences: $vectorOfNonOwningReferences, anyUniqueType: $anyUniqueType, anyUnique: $anyUnique, anyAmbiguousType: $anyAmbiguousType, anyAmbiguous: $anyAmbiguous, vectorOfEnums: $vectorOfEnums, signedEnum: $signedEnum, testrequirednestedflatbuffer: $testrequirednestedflatbuffer, scalarKeySortedTables: $scalarKeySortedTables}';
return 'Monster{pos: ${pos}, mana: ${mana}, hp: ${hp}, name: ${name}, inventory: ${inventory}, color: ${color}, testType: ${testType}, test: ${test}, test4: ${test4}, testarrayofstring: ${testarrayofstring}, testarrayoftables: ${testarrayoftables}, enemy: ${enemy}, testnestedflatbuffer: ${testnestedflatbuffer}, testempty: ${testempty}, testbool: ${testbool}, testhashs32Fnv1: ${testhashs32Fnv1}, testhashu32Fnv1: ${testhashu32Fnv1}, testhashs64Fnv1: ${testhashs64Fnv1}, testhashu64Fnv1: ${testhashu64Fnv1}, testhashs32Fnv1a: ${testhashs32Fnv1a}, testhashu32Fnv1a: ${testhashu32Fnv1a}, testhashs64Fnv1a: ${testhashs64Fnv1a}, testhashu64Fnv1a: ${testhashu64Fnv1a}, testarrayofbools: ${testarrayofbools}, testf: ${testf}, testf2: ${testf2}, testf3: ${testf3}, testarrayofstring2: ${testarrayofstring2}, testarrayofsortedstruct: ${testarrayofsortedstruct}, flex: ${flex}, test5: ${test5}, vectorOfLongs: ${vectorOfLongs}, vectorOfDoubles: ${vectorOfDoubles}, parentNamespaceTest: ${parentNamespaceTest}, vectorOfReferrables: ${vectorOfReferrables}, singleWeakReference: ${singleWeakReference}, vectorOfWeakReferences: ${vectorOfWeakReferences}, vectorOfStrongReferrables: ${vectorOfStrongReferrables}, coOwningReference: ${coOwningReference}, vectorOfCoOwningReferences: ${vectorOfCoOwningReferences}, nonOwningReference: ${nonOwningReference}, vectorOfNonOwningReferences: ${vectorOfNonOwningReferences}, anyUniqueType: ${anyUniqueType}, anyUnique: ${anyUnique}, anyAmbiguousType: ${anyAmbiguousType}, anyAmbiguous: ${anyAmbiguous}, vectorOfEnums: ${vectorOfEnums}, signedEnum: ${signedEnum}, testrequirednestedflatbuffer: ${testrequirednestedflatbuffer}, scalarKeySortedTables: ${scalarKeySortedTables}, nativeInline: ${nativeInline}, longEnumNonEnumDefault: ${longEnumNonEnumDefault}, longEnumNormalDefault: ${longEnumNormalDefault}, nanDefault: ${nanDefault}, infDefault: ${infDefault}, positiveInfDefault: ${positiveInfDefault}, infinityDefault: ${infinityDefault}, positiveInfinityDefault: ${positiveInfinityDefault}, negativeInfDefault: ${negativeInfDefault}, negativeInfinityDefault: ${negativeInfinityDefault}, doubleInfDefault: ${doubleInfDefault}}';
}
MonsterT unpack() => MonsterT(
@@ -1171,7 +1324,18 @@ class Monster {
vectorOfEnums: const fb.ListReader<Color>(Color.reader, lazy: false).vTableGetNullable(_bc, _bcOffset, 98),
signedEnum: signedEnum,
testrequirednestedflatbuffer: const fb.Uint8ListReader(lazy: false).vTableGetNullable(_bc, _bcOffset, 102),
scalarKeySortedTables: scalarKeySortedTables?.map((e) => e.unpack()).toList());
scalarKeySortedTables: scalarKeySortedTables?.map((e) => e.unpack()).toList(),
nativeInline: nativeInline?.unpack(),
longEnumNonEnumDefault: longEnumNonEnumDefault,
longEnumNormalDefault: longEnumNormalDefault,
nanDefault: nanDefault,
infDefault: infDefault,
positiveInfDefault: positiveInfDefault,
infinityDefault: infinityDefault,
positiveInfinityDefault: positiveInfinityDefault,
negativeInfDefault: negativeInfDefault,
negativeInfinityDefault: negativeInfinityDefault,
doubleInfDefault: doubleInfDefault);
static int pack(fb.Builder fbBuilder, MonsterT? object) {
if (object == null) return 0;
@@ -1233,6 +1397,17 @@ class MonsterT implements fb.Packable {
Race signedEnum;
List<int>? testrequirednestedflatbuffer;
List<StatT>? scalarKeySortedTables;
TestT? nativeInline;
LongEnum longEnumNonEnumDefault;
LongEnum longEnumNormalDefault;
double nanDefault;
double infDefault;
double positiveInfDefault;
double infinityDefault;
double positiveInfinityDefault;
double negativeInfDefault;
double negativeInfinityDefault;
double doubleInfDefault;
MonsterT({
this.pos,
@@ -1284,7 +1459,18 @@ class MonsterT implements fb.Packable {
this.vectorOfEnums,
this.signedEnum = Race.None,
this.testrequirednestedflatbuffer,
this.scalarKeySortedTables});
this.scalarKeySortedTables,
this.nativeInline,
this.longEnumNonEnumDefault = const LongEnum._(0),
this.longEnumNormalDefault = LongEnum.LongOne,
this.nanDefault = double.nan,
this.infDefault = double.infinity,
this.positiveInfDefault = double.infinity,
this.infinityDefault = double.infinity,
this.positiveInfinityDefault = double.infinity,
this.negativeInfDefault = double.negativeInfinity,
this.negativeInfinityDefault = double.negativeInfinity,
this.doubleInfDefault = double.infinity});
@override
int pack(fb.Builder fbBuilder) {
@@ -1345,7 +1531,7 @@ class MonsterT implements fb.Packable {
: fbBuilder.writeListUint8(testrequirednestedflatbuffer!);
final int? scalarKeySortedTablesOffset = scalarKeySortedTables == null ? null
: fbBuilder.writeList(scalarKeySortedTables!.map((b) => b.pack(fbBuilder)).toList());
fbBuilder.startTable(50);
fbBuilder.startTable(62);
if (pos != null) {
fbBuilder.addStruct(0, pos!.pack(fbBuilder));
}
@@ -1398,12 +1584,25 @@ class MonsterT implements fb.Packable {
fbBuilder.addInt8(48, signedEnum.value);
fbBuilder.addOffset(49, testrequirednestedflatbufferOffset);
fbBuilder.addOffset(50, scalarKeySortedTablesOffset);
if (nativeInline != null) {
fbBuilder.addStruct(51, nativeInline!.pack(fbBuilder));
}
fbBuilder.addUint64(52, longEnumNonEnumDefault.value);
fbBuilder.addUint64(53, longEnumNormalDefault.value);
fbBuilder.addFloat32(54, nanDefault);
fbBuilder.addFloat32(55, infDefault);
fbBuilder.addFloat32(56, positiveInfDefault);
fbBuilder.addFloat32(57, infinityDefault);
fbBuilder.addFloat32(58, positiveInfinityDefault);
fbBuilder.addFloat32(59, negativeInfDefault);
fbBuilder.addFloat32(60, negativeInfinityDefault);
fbBuilder.addFloat64(61, doubleInfDefault);
return fbBuilder.endTable();
}
@override
String toString() {
return 'MonsterT{pos: $pos, mana: $mana, hp: $hp, name: $name, inventory: $inventory, color: $color, testType: $testType, test: $test, test4: $test4, testarrayofstring: $testarrayofstring, testarrayoftables: $testarrayoftables, enemy: $enemy, testnestedflatbuffer: $testnestedflatbuffer, testempty: $testempty, testbool: $testbool, testhashs32Fnv1: $testhashs32Fnv1, testhashu32Fnv1: $testhashu32Fnv1, testhashs64Fnv1: $testhashs64Fnv1, testhashu64Fnv1: $testhashu64Fnv1, testhashs32Fnv1a: $testhashs32Fnv1a, testhashu32Fnv1a: $testhashu32Fnv1a, testhashs64Fnv1a: $testhashs64Fnv1a, testhashu64Fnv1a: $testhashu64Fnv1a, testarrayofbools: $testarrayofbools, testf: $testf, testf2: $testf2, testf3: $testf3, testarrayofstring2: $testarrayofstring2, testarrayofsortedstruct: $testarrayofsortedstruct, flex: $flex, test5: $test5, vectorOfLongs: $vectorOfLongs, vectorOfDoubles: $vectorOfDoubles, parentNamespaceTest: $parentNamespaceTest, vectorOfReferrables: $vectorOfReferrables, singleWeakReference: $singleWeakReference, vectorOfWeakReferences: $vectorOfWeakReferences, vectorOfStrongReferrables: $vectorOfStrongReferrables, coOwningReference: $coOwningReference, vectorOfCoOwningReferences: $vectorOfCoOwningReferences, nonOwningReference: $nonOwningReference, vectorOfNonOwningReferences: $vectorOfNonOwningReferences, anyUniqueType: $anyUniqueType, anyUnique: $anyUnique, anyAmbiguousType: $anyAmbiguousType, anyAmbiguous: $anyAmbiguous, vectorOfEnums: $vectorOfEnums, signedEnum: $signedEnum, testrequirednestedflatbuffer: $testrequirednestedflatbuffer, scalarKeySortedTables: $scalarKeySortedTables}';
return 'MonsterT{pos: ${pos}, mana: ${mana}, hp: ${hp}, name: ${name}, inventory: ${inventory}, color: ${color}, testType: ${testType}, test: ${test}, test4: ${test4}, testarrayofstring: ${testarrayofstring}, testarrayoftables: ${testarrayoftables}, enemy: ${enemy}, testnestedflatbuffer: ${testnestedflatbuffer}, testempty: ${testempty}, testbool: ${testbool}, testhashs32Fnv1: ${testhashs32Fnv1}, testhashu32Fnv1: ${testhashu32Fnv1}, testhashs64Fnv1: ${testhashs64Fnv1}, testhashu64Fnv1: ${testhashu64Fnv1}, testhashs32Fnv1a: ${testhashs32Fnv1a}, testhashu32Fnv1a: ${testhashu32Fnv1a}, testhashs64Fnv1a: ${testhashs64Fnv1a}, testhashu64Fnv1a: ${testhashu64Fnv1a}, testarrayofbools: ${testarrayofbools}, testf: ${testf}, testf2: ${testf2}, testf3: ${testf3}, testarrayofstring2: ${testarrayofstring2}, testarrayofsortedstruct: ${testarrayofsortedstruct}, flex: ${flex}, test5: ${test5}, vectorOfLongs: ${vectorOfLongs}, vectorOfDoubles: ${vectorOfDoubles}, parentNamespaceTest: ${parentNamespaceTest}, vectorOfReferrables: ${vectorOfReferrables}, singleWeakReference: ${singleWeakReference}, vectorOfWeakReferences: ${vectorOfWeakReferences}, vectorOfStrongReferrables: ${vectorOfStrongReferrables}, coOwningReference: ${coOwningReference}, vectorOfCoOwningReferences: ${vectorOfCoOwningReferences}, nonOwningReference: ${nonOwningReference}, vectorOfNonOwningReferences: ${vectorOfNonOwningReferences}, anyUniqueType: ${anyUniqueType}, anyUnique: ${anyUnique}, anyAmbiguousType: ${anyAmbiguousType}, anyAmbiguous: ${anyAmbiguous}, vectorOfEnums: ${vectorOfEnums}, signedEnum: ${signedEnum}, testrequirednestedflatbuffer: ${testrequirednestedflatbuffer}, scalarKeySortedTables: ${scalarKeySortedTables}, nativeInline: ${nativeInline}, longEnumNonEnumDefault: ${longEnumNonEnumDefault}, longEnumNormalDefault: ${longEnumNormalDefault}, nanDefault: ${nanDefault}, infDefault: ${infDefault}, positiveInfDefault: ${positiveInfDefault}, infinityDefault: ${infinityDefault}, positiveInfinityDefault: ${positiveInfinityDefault}, negativeInfDefault: ${negativeInfDefault}, negativeInfinityDefault: ${negativeInfinityDefault}, doubleInfDefault: ${doubleInfDefault}}';
}
}
@@ -1421,7 +1620,7 @@ class MonsterBuilder {
final fb.Builder fbBuilder;
void begin() {
fbBuilder.startTable(50);
fbBuilder.startTable(62);
}
int addPos(int offset) {
@@ -1624,6 +1823,50 @@ class MonsterBuilder {
fbBuilder.addOffset(50, offset);
return fbBuilder.offset;
}
int addNativeInline(int offset) {
fbBuilder.addStruct(51, offset);
return fbBuilder.offset;
}
int addLongEnumNonEnumDefault(LongEnum? longEnumNonEnumDefault) {
fbBuilder.addUint64(52, longEnumNonEnumDefault?.value);
return fbBuilder.offset;
}
int addLongEnumNormalDefault(LongEnum? longEnumNormalDefault) {
fbBuilder.addUint64(53, longEnumNormalDefault?.value);
return fbBuilder.offset;
}
int addNanDefault(double? nanDefault) {
fbBuilder.addFloat32(54, nanDefault);
return fbBuilder.offset;
}
int addInfDefault(double? infDefault) {
fbBuilder.addFloat32(55, infDefault);
return fbBuilder.offset;
}
int addPositiveInfDefault(double? positiveInfDefault) {
fbBuilder.addFloat32(56, positiveInfDefault);
return fbBuilder.offset;
}
int addInfinityDefault(double? infinityDefault) {
fbBuilder.addFloat32(57, infinityDefault);
return fbBuilder.offset;
}
int addPositiveInfinityDefault(double? positiveInfinityDefault) {
fbBuilder.addFloat32(58, positiveInfinityDefault);
return fbBuilder.offset;
}
int addNegativeInfDefault(double? negativeInfDefault) {
fbBuilder.addFloat32(59, negativeInfDefault);
return fbBuilder.offset;
}
int addNegativeInfinityDefault(double? negativeInfinityDefault) {
fbBuilder.addFloat32(60, negativeInfinityDefault);
return fbBuilder.offset;
}
int addDoubleInfDefault(double? doubleInfDefault) {
fbBuilder.addFloat64(61, doubleInfDefault);
return fbBuilder.offset;
}
int finish() {
return fbBuilder.endTable();
@@ -1681,6 +1924,17 @@ class MonsterObjectBuilder extends fb.ObjectBuilder {
final Race? _signedEnum;
final List<int>? _testrequirednestedflatbuffer;
final List<StatObjectBuilder>? _scalarKeySortedTables;
final TestObjectBuilder? _nativeInline;
final LongEnum? _longEnumNonEnumDefault;
final LongEnum? _longEnumNormalDefault;
final double? _nanDefault;
final double? _infDefault;
final double? _positiveInfDefault;
final double? _infinityDefault;
final double? _positiveInfinityDefault;
final double? _negativeInfDefault;
final double? _negativeInfinityDefault;
final double? _doubleInfDefault;
MonsterObjectBuilder({
Vec3ObjectBuilder? pos,
@@ -1733,6 +1987,17 @@ class MonsterObjectBuilder extends fb.ObjectBuilder {
Race? signedEnum,
List<int>? testrequirednestedflatbuffer,
List<StatObjectBuilder>? scalarKeySortedTables,
TestObjectBuilder? nativeInline,
LongEnum? longEnumNonEnumDefault,
LongEnum? longEnumNormalDefault,
double? nanDefault,
double? infDefault,
double? positiveInfDefault,
double? infinityDefault,
double? positiveInfinityDefault,
double? negativeInfDefault,
double? negativeInfinityDefault,
double? doubleInfDefault,
})
: _pos = pos,
_mana = mana,
@@ -1783,7 +2048,18 @@ class MonsterObjectBuilder extends fb.ObjectBuilder {
_vectorOfEnums = vectorOfEnums,
_signedEnum = signedEnum,
_testrequirednestedflatbuffer = testrequirednestedflatbuffer,
_scalarKeySortedTables = scalarKeySortedTables;
_scalarKeySortedTables = scalarKeySortedTables,
_nativeInline = nativeInline,
_longEnumNonEnumDefault = longEnumNonEnumDefault,
_longEnumNormalDefault = longEnumNormalDefault,
_nanDefault = nanDefault,
_infDefault = infDefault,
_positiveInfDefault = positiveInfDefault,
_infinityDefault = infinityDefault,
_positiveInfinityDefault = positiveInfinityDefault,
_negativeInfDefault = negativeInfDefault,
_negativeInfinityDefault = negativeInfinityDefault,
_doubleInfDefault = doubleInfDefault;
/// Finish building, and store into the [fbBuilder].
@override
@@ -1836,7 +2112,7 @@ class MonsterObjectBuilder extends fb.ObjectBuilder {
: fbBuilder.writeListUint8(_testrequirednestedflatbuffer!);
final int? scalarKeySortedTablesOffset = _scalarKeySortedTables == null ? null
: fbBuilder.writeList(_scalarKeySortedTables!.map((b) => b.getOrCreateOffset(fbBuilder)).toList());
fbBuilder.startTable(50);
fbBuilder.startTable(62);
if (_pos != null) {
fbBuilder.addStruct(0, _pos!.finish(fbBuilder));
}
@@ -1889,6 +2165,19 @@ class MonsterObjectBuilder extends fb.ObjectBuilder {
fbBuilder.addInt8(48, _signedEnum?.value);
fbBuilder.addOffset(49, testrequirednestedflatbufferOffset);
fbBuilder.addOffset(50, scalarKeySortedTablesOffset);
if (_nativeInline != null) {
fbBuilder.addStruct(51, _nativeInline!.finish(fbBuilder));
}
fbBuilder.addUint64(52, _longEnumNonEnumDefault?.value);
fbBuilder.addUint64(53, _longEnumNormalDefault?.value);
fbBuilder.addFloat32(54, _nanDefault);
fbBuilder.addFloat32(55, _infDefault);
fbBuilder.addFloat32(56, _positiveInfDefault);
fbBuilder.addFloat32(57, _infinityDefault);
fbBuilder.addFloat32(58, _positiveInfinityDefault);
fbBuilder.addFloat32(59, _negativeInfDefault);
fbBuilder.addFloat32(60, _negativeInfinityDefault);
fbBuilder.addFloat64(61, _doubleInfDefault);
return fbBuilder.endTable();
}
@@ -1927,7 +2216,7 @@ class TypeAliases {
@override
String toString() {
return 'TypeAliases{i8: $i8, u8: $u8, i16: $i16, u16: $u16, i32: $i32, u32: $u32, i64: $i64, u64: $u64, f32: $f32, f64: $f64, v8: $v8, vf64: $vf64}';
return 'TypeAliases{i8: ${i8}, u8: ${u8}, i16: ${i16}, u16: ${u16}, i32: ${i32}, u32: ${u32}, i64: ${i64}, u64: ${u64}, f32: ${f32}, f64: ${f64}, v8: ${v8}, vf64: ${vf64}}';
}
TypeAliasesT unpack() => TypeAliasesT(
@@ -2002,7 +2291,7 @@ class TypeAliasesT implements fb.Packable {
@override
String toString() {
return 'TypeAliasesT{i8: $i8, u8: $u8, i16: $i16, u16: $u16, i32: $i32, u32: $u32, i64: $i64, u64: $u64, f32: $f32, f64: $f64, v8: $v8, vf64: $vf64}';
return 'TypeAliasesT{i8: ${i8}, u8: ${u8}, i16: ${i16}, u16: ${u16}, i32: ${i32}, u32: ${u32}, i64: ${i64}, u64: ${u64}, f32: ${f32}, f64: ${f64}, v8: ${v8}, vf64: ${vf64}}';
}
}

View File

@@ -9,6 +9,8 @@ import 'package:flat_buffers/flat_buffers.dart' as fb;
import './monster_test_my_game.example_generated.dart' as my_game_example;
import './monster_test_my_game.example2_generated.dart' as my_game_example2;
import './include_test1_generated.dart';
class InParentNamespace {
InParentNamespace._(this._bc, this._bcOffset);
factory InParentNamespace(List<int> bytes) {

Binary file not shown.

View File

@@ -90,7 +90,10 @@ Additional options:
- `--scoped-enums` : Use C++11 style scoped and strongly typed enums in
generated C++. This also implies `--no-prefix`.
- `--no-emit-min-max-enum-values` : Disable generation of MIN and MAX
enumerated values for scoped enums and prefixed enums.
- `--gen-includes` : (deprecated), this is the default behavior.
If the original behavior is required (no include
statements) use `--no-includes.`

View File

@@ -82,7 +82,7 @@ pass to the `GetRootAsMyRootType` function:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cs}
using MyGame.Example;
using FlatBuffers;
using Google.FlatBuffers;
// This snippet ignores exceptions for brevity.
byte[] data = File.ReadAllBytes("monsterdata_test.mon");

View File

@@ -10,7 +10,7 @@ include = `include` string\_constant `;`
namespace\_decl = `namespace` ident ( `.` ident )* `;`
attribute\_decl = `attribute` ident | `"`ident`"` `;`
attribute\_decl = `attribute` ident | `"` ident `"` `;`
type\_decl = ( `table` | `struct` ) ident metadata `{` field\_decl+ `}`
@@ -31,7 +31,7 @@ type = `bool` | `byte` | `ubyte` | `short` | `ushort` | `int` | `uint` |
`float32` | `float64` |
`string` | `[` type `]` | ident
enumval\_decl = ident [ `=` integer\_constant ]
enumval\_decl = ident [ `=` integer\_constant ] metadata
metadata = [ `(` commasep( ident [ `:` single\_value ] ) `)` ]

View File

@@ -4,7 +4,7 @@ To generate the docs for FlatBuffers from the source files, you
will first need to install two programs.
1. You will need to install `doxygen`. See
[Download Doxygen](http://www.stack.nl/~dimitri/doxygen/download.html).
[Download Doxygen](https://doxygen.nl/download.html).
2. You will need to install `doxypypy` to format python comments appropriately.
Install it from [here](https://github.com/Feneric/doxypypy).

View File

@@ -309,11 +309,11 @@ in the corresponding C++ code. Multiple such lines per item are allowed.
### Attributes
Attributes may be attached to a declaration, behind a field, or after
the name of a table/struct/enum/union. These may either have a value or
not. Some attributes like `deprecated` are understood by the compiler;
user defined ones need to be declared with the attribute declaration
(like `priority` in the example above), and are
Attributes may be attached to a declaration, behind a field/enum value,
or after the name of a table/struct/enum/union. These may either have
a value or not. Some attributes like `deprecated` are understood by
the compiler; user defined ones need to be declared with the attribute
declaration (like `priority` in the example above), and are
available to query if you parse the schema at runtime.
This is useful if you write your own code generators/editors etc., and
you wish to add additional information specific to your tool (such as a
@@ -552,7 +552,7 @@ the world. If this is not practical for you, use explicit field ids, which
should always generate a merge conflict if two people try to allocate the same
id.
### Schema evolution examples
### Schema evolution examples (tables)
Some examples to clarify what happens as you change a schema:
@@ -614,6 +614,41 @@ Occasionally ok. You've renamed fields, which will break all code (and JSON
files!) that use this schema, but as long as the change is obvious, this is not
incompatible with the actual binary buffers, since those only ever address
fields by id/offset.
#### Schema evolution examples (unions)
Suppose we have the following schema:
```
union Foo { A, B }
```
We can add another variant at the end.
```
union Foo { A, B, another_a: A }
```
and this will be okay. Old code will not recognize `another_a`.
However if we add `another_a` anywhere but the end, e.g.
```
union Foo { A, another_a: A, B }
```
this is not okay. When new code writes `another_a`, old code will
misinterpret it as `B` (and vice versa). However you can explicitly
set the union's "discriminant" value like so:
```
union Foo { A = 1, another_a: A = 3, B = 2 }
```
This is okay.
```
union Foo { original_a: A = 1, another_a: A = 3, B = 2 }
```
Renaming fields will break code and any saved human readable representations,
such as json files, but the binary buffers will be the same.
<br>
### Testing whether a field is present in a table

View File

@@ -22,10 +22,10 @@ GitHub page](https://github.com/google/flatbuffers/tree/master/swift).
## Testing the FlatBuffers Swift library
The code to test the Swift library can be found at `flatbuffers/Flatbuffers.Test.Swift`.
The test code itself is located in [Flatbuffers.Test.Swift](https://github.com/google/flatbuffers/blob/master/tests/FlatBuffers.Test.Swift).
The code to test the Swift library can be found at `flatbuffers/tests/swift/tests`.
The test code itself is located in [flatbuffers/tests/swift/tests](https://github.com/google/flatbuffers/blob/master/tests/swift/tests).
To run the tests, use the [SwiftTest.sh](https://github.com/google/flatbuffers/blob/master/tests/FlatBuffers.Test.Swift/SwiftTest.sh) shell script.
To run the tests, use the [SwiftTest.sh](https://github.com/google/flatbuffers/blob/master/tests/swift/tests/SwiftTest.sh) shell script.
*Note: The shell script requires [Swift](https://swift.org) to
be installed.*
@@ -72,7 +72,10 @@ Now you can access values like this:
In some cases it's necessary to modify values in an existing FlatBuffer in place (without creating a copy). For this reason, scalar fields of a Flatbuffer table or struct can be mutated.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.swift}
let monster = Monster.getRootAsMonster(bb: ByteBuffer(data: data))
var byteBuffer = ByteBuffer(bytes: data)
// Get an accessor to the root object inside the buffer.
let monster: Monster = try! getCheckedRoot(byteBuffer: &byteBuffer)
// let monster: Monster = getRoot(byteBuffer: &byteBuffer)
if !monster.mutate(hp: 10) {
fatalError("couldn't mutate")

View File

@@ -415,7 +415,7 @@ The first step is to import/include the library, generated files, etc.
</div>
<div class="language-csharp">
~~~{.cs}
using FlatBuffers;
using Google.FlatBuffers;
using MyGame.Sample; // The `flatc` generated files. (Monster, Vec3, etc.)
~~~
</div>
@@ -2200,7 +2200,7 @@ before:
</div>
<div class="language-csharp">
~~~{.cs}
using FlatBuffers;
using Google.FlatBuffers;
using MyGame.Sample; // The `flatc` generated files. (Monster, Vec3, etc.)
~~~
</div>
@@ -2472,10 +2472,10 @@ myGame.Monster monster = new myGame.Monster(data);
<div class="language-swift">
~~~{.swift}
// create a ByteBuffer(:) from an [UInt8] or Data()
let buf = // Get your data
var buf = // Get your data
// Get an accessor to the root object inside the buffer.
let monster = Monster.getRootAsMonster(bb: ByteBuffer(bytes: buf))
let monster: Monster = try! getCheckedRoot(byteBuffer: &byteBuffer)
// let monster: Monster = getRoot(byteBuffer: &byteBuffer)
~~~
</div>
@@ -3449,7 +3449,7 @@ Java supports vectors of unions, but it isn't currently documented.
</div>
<div class="language-csharp">
~~~{.cs}
using FlatBuffers;
using Google.FlatBuffers;
using Example.VectorOfUnions;
var fbb = new FlatBufferBuilder(100);

View File

@@ -0,0 +1,27 @@
# Go Echo Example
A simple example demonstrating how to send flatbuffers over the network in Go.
## Generate flatbuffer code
```
flatc -g --gen-object-api --go-module-name echo hero.fbs net.fbs
```
## Running example
1. Run go mod tidy to get dependencies
```
go mod tidy
```
2. Start a server
```
go run server/server.go
```
3. Run the client in another terminal
```
go run client/client.go
```

View File

@@ -0,0 +1,51 @@
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"echo/hero"
"echo/net"
flatbuffers "github.com/google/flatbuffers/go"
)
func RequestBody() *bytes.Reader {
b := flatbuffers.NewBuilder(0)
r := net.RequestT{Player: &hero.WarriorT{Name: "Krull", Hp: 100}}
b.Finish(r.Pack(b))
return bytes.NewReader(b.FinishedBytes())
}
func ReadResponse(r *http.Response) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Printf("Unable to read request body: %v\n", err)
return
}
res := net.GetRootAsResponse(body, 0)
player := res.Player(nil)
fmt.Printf("Got response (name: %v, hp: %v)\n", string(player.Name()), player.Hp())
}
func main() {
body := RequestBody()
req, err := http.NewRequest("POST", "http://localhost:8080/echo", body)
if err != nil {
fmt.Println(err)
return
}
client := http.DefaultClient
resp, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
ReadResponse(resp)
}

5
examples/go-echo/go.mod Normal file
View File

@@ -0,0 +1,5 @@
module echo
go 1.19
require github.com/google/flatbuffers v22.10.26+incompatible

View File

@@ -0,0 +1,6 @@
namespace hero;
table Warrior {
name: string;
hp: uint32;
}

View File

@@ -0,0 +1,93 @@
// Code generated by the FlatBuffers compiler. DO NOT EDIT.
package hero
import (
flatbuffers "github.com/google/flatbuffers/go"
)
type WarriorT struct {
Name string `json:"name"`
Hp uint32 `json:"hp"`
}
func (t *WarriorT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
if t == nil { return 0 }
nameOffset := builder.CreateString(t.Name)
WarriorStart(builder)
WarriorAddName(builder, nameOffset)
WarriorAddHp(builder, t.Hp)
return WarriorEnd(builder)
}
func (rcv *Warrior) UnPackTo(t *WarriorT) {
t.Name = string(rcv.Name())
t.Hp = rcv.Hp()
}
func (rcv *Warrior) UnPack() *WarriorT {
if rcv == nil { return nil }
t := &WarriorT{}
rcv.UnPackTo(t)
return t
}
type Warrior struct {
_tab flatbuffers.Table
}
func GetRootAsWarrior(buf []byte, offset flatbuffers.UOffsetT) *Warrior {
n := flatbuffers.GetUOffsetT(buf[offset:])
x := &Warrior{}
x.Init(buf, n+offset)
return x
}
func GetSizePrefixedRootAsWarrior(buf []byte, offset flatbuffers.UOffsetT) *Warrior {
n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:])
x := &Warrior{}
x.Init(buf, n+offset+flatbuffers.SizeUint32)
return x
}
func (rcv *Warrior) Init(buf []byte, i flatbuffers.UOffsetT) {
rcv._tab.Bytes = buf
rcv._tab.Pos = i
}
func (rcv *Warrior) Table() flatbuffers.Table {
return rcv._tab
}
func (rcv *Warrior) Name() []byte {
o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
if o != 0 {
return rcv._tab.ByteVector(o + rcv._tab.Pos)
}
return nil
}
func (rcv *Warrior) Hp() uint32 {
o := flatbuffers.UOffsetT(rcv._tab.Offset(6))
if o != 0 {
return rcv._tab.GetUint32(o + rcv._tab.Pos)
}
return 0
}
func (rcv *Warrior) MutateHp(n uint32) bool {
return rcv._tab.MutateUint32Slot(6, n)
}
func WarriorStart(builder *flatbuffers.Builder) {
builder.StartObject(2)
}
func WarriorAddName(builder *flatbuffers.Builder, name flatbuffers.UOffsetT) {
builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(name), 0)
}
func WarriorAddHp(builder *flatbuffers.Builder, hp uint32) {
builder.PrependUint32Slot(1, hp, 0)
}
func WarriorEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
return builder.EndObject()
}

11
examples/go-echo/net.fbs Normal file
View File

@@ -0,0 +1,11 @@
include "hero.fbs";
namespace net;
table Request {
player: hero.Warrior;
}
table Response {
player: hero.Warrior;
}

View File

@@ -0,0 +1,82 @@
// Code generated by the FlatBuffers compiler. DO NOT EDIT.
package net
import (
flatbuffers "github.com/google/flatbuffers/go"
hero "echo/hero"
)
type RequestT struct {
Player *hero.WarriorT `json:"player"`
}
func (t *RequestT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
if t == nil { return 0 }
playerOffset := t.Player.Pack(builder)
RequestStart(builder)
RequestAddPlayer(builder, playerOffset)
return RequestEnd(builder)
}
func (rcv *Request) UnPackTo(t *RequestT) {
t.Player = rcv.Player(nil).UnPack()
}
func (rcv *Request) UnPack() *RequestT {
if rcv == nil { return nil }
t := &RequestT{}
rcv.UnPackTo(t)
return t
}
type Request struct {
_tab flatbuffers.Table
}
func GetRootAsRequest(buf []byte, offset flatbuffers.UOffsetT) *Request {
n := flatbuffers.GetUOffsetT(buf[offset:])
x := &Request{}
x.Init(buf, n+offset)
return x
}
func GetSizePrefixedRootAsRequest(buf []byte, offset flatbuffers.UOffsetT) *Request {
n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:])
x := &Request{}
x.Init(buf, n+offset+flatbuffers.SizeUint32)
return x
}
func (rcv *Request) Init(buf []byte, i flatbuffers.UOffsetT) {
rcv._tab.Bytes = buf
rcv._tab.Pos = i
}
func (rcv *Request) Table() flatbuffers.Table {
return rcv._tab
}
func (rcv *Request) Player(obj *hero.Warrior) *hero.Warrior {
o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
if o != 0 {
x := rcv._tab.Indirect(o + rcv._tab.Pos)
if obj == nil {
obj = new(hero.Warrior)
}
obj.Init(rcv._tab.Bytes, x)
return obj
}
return nil
}
func RequestStart(builder *flatbuffers.Builder) {
builder.StartObject(1)
}
func RequestAddPlayer(builder *flatbuffers.Builder, player flatbuffers.UOffsetT) {
builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(player), 0)
}
func RequestEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
return builder.EndObject()
}

View File

@@ -0,0 +1,82 @@
// Code generated by the FlatBuffers compiler. DO NOT EDIT.
package net
import (
flatbuffers "github.com/google/flatbuffers/go"
hero "echo/hero"
)
type ResponseT struct {
Player *hero.WarriorT `json:"player"`
}
func (t *ResponseT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
if t == nil { return 0 }
playerOffset := t.Player.Pack(builder)
ResponseStart(builder)
ResponseAddPlayer(builder, playerOffset)
return ResponseEnd(builder)
}
func (rcv *Response) UnPackTo(t *ResponseT) {
t.Player = rcv.Player(nil).UnPack()
}
func (rcv *Response) UnPack() *ResponseT {
if rcv == nil { return nil }
t := &ResponseT{}
rcv.UnPackTo(t)
return t
}
type Response struct {
_tab flatbuffers.Table
}
func GetRootAsResponse(buf []byte, offset flatbuffers.UOffsetT) *Response {
n := flatbuffers.GetUOffsetT(buf[offset:])
x := &Response{}
x.Init(buf, n+offset)
return x
}
func GetSizePrefixedRootAsResponse(buf []byte, offset flatbuffers.UOffsetT) *Response {
n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:])
x := &Response{}
x.Init(buf, n+offset+flatbuffers.SizeUint32)
return x
}
func (rcv *Response) Init(buf []byte, i flatbuffers.UOffsetT) {
rcv._tab.Bytes = buf
rcv._tab.Pos = i
}
func (rcv *Response) Table() flatbuffers.Table {
return rcv._tab
}
func (rcv *Response) Player(obj *hero.Warrior) *hero.Warrior {
o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
if o != 0 {
x := rcv._tab.Indirect(o + rcv._tab.Pos)
if obj == nil {
obj = new(hero.Warrior)
}
obj.Init(rcv._tab.Bytes, x)
return obj
}
return nil
}
func ResponseStart(builder *flatbuffers.Builder) {
builder.StartObject(1)
}
func ResponseAddPlayer(builder *flatbuffers.Builder, player flatbuffers.UOffsetT) {
builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(player), 0)
}
func ResponseEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
return builder.EndObject()
}

View File

@@ -0,0 +1,29 @@
package main
import (
"echo/net"
"fmt"
"io/ioutil"
"net/http"
)
func echo(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Printf("Unable to read request body: %v\n", err)
return
}
req := net.GetRootAsRequest(body, 0)
player := req.Player(nil)
fmt.Printf("Got request (name: %v, hp: %v)\n", string(player.Name()), player.Hp())
w.Write(body)
}
func main() {
http.HandleFunc("/echo", echo)
fmt.Println("Listening on port :8080")
http.ListenAndServe(":8080", nil)
}

View File

@@ -1,5 +1,7 @@
package flatbuffers
import "sort"
// Builder is a state machine for creating FlatBuffer objects.
// Use a Builder to construct object(s) starting from leaf nodes.
//
@@ -315,6 +317,25 @@ func (b *Builder) EndVector(vectorNumElems int) UOffsetT {
return b.Offset()
}
// CreateVectorOfTables serializes slice of table offsets into a vector.
func (b *Builder) CreateVectorOfTables(offsets []UOffsetT) UOffsetT {
b.assertNotNested()
b.StartVector(4, len(offsets), 4)
for i := len(offsets) - 1; i >= 0; i-- {
b.PrependUOffsetT(offsets[i])
}
return b.EndVector(len(offsets))
}
type KeyCompare func(o1, o2 UOffsetT, buf []byte) bool
func (b *Builder) CreateVectorOfSortedTables(offsets []UOffsetT, keyCompare KeyCompare) UOffsetT {
sort.Slice(offsets, func(i, j int) bool {
return keyCompare(offsets[i], offsets[j], b.Bytes)
})
return b.CreateVectorOfTables(offsets)
}
// CreateSharedString Checks if the string is already written
// to the buffer before calling CreateString
func (b *Builder) CreateSharedString(s string) UOffsetT {

View File

@@ -23,3 +23,8 @@ func GetSizePrefixedRootAs(buf []byte, offset UOffsetT, fb FlatBuffer) {
func GetSizePrefix(buf []byte, offset UOffsetT) uint32 {
return GetUint32(buf[offset:])
}
// GetIndirectOffset retrives the relative offset in the provided buffer stored at `offset`.
func GetIndirectOffset(buf []byte, offset UOffsetT) UOffsetT {
return offset + GetUOffsetT(buf[offset:])
}

View File

@@ -0,0 +1,10 @@
diff --git a/bazel/copts.bzl b/bazel/copts.bzl
index 10be944f25..879518b92f 100644
--- a/bazel/copts.bzl
+++ b/bazel/copts.bzl
@@ -59,4 +59,4 @@ GRPC_LLVM_WARNING_FLAGS = [
GRPC_DEFAULT_COPTS = select({
"//:use_strict_warning": GRPC_LLVM_WARNING_FLAGS + ["-DUSE_STRICT_WARNING=1"],
"//conditions:default": [],
-})
+}) + ["-std=c++14"]

View File

@@ -6,12 +6,10 @@ import FlatBuffers
public struct models_HelloReply: FlatBufferObject, Verifiable {
static func validateVersion() { FlatBuffersVersion_2_0_8() }
static func validateVersion() { FlatBuffersVersion_23_1_20() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table
public static func getRootAsHelloReply(bb: ByteBuffer) -> models_HelloReply { return models_HelloReply(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
private init(_ t: Table) { _accessor = t }
public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
@@ -55,12 +53,10 @@ extension models_HelloReply: Encodable {
public struct models_HelloRequest: FlatBufferObject, Verifiable {
static func validateVersion() { FlatBuffersVersion_2_0_8() }
static func validateVersion() { FlatBuffersVersion_23_1_20() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table
public static func getRootAsHelloRequest(bb: ByteBuffer) -> models_HelloRequest { return models_HelloRequest(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
private init(_ t: Table) { _accessor = t }
public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2021 Google Inc. All rights reserved.
* Copyright 2023 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2021 Google Inc. All rights reserved.
* Copyright 2023 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@@ -1,4 +1,4 @@
// automatically generated by the FlatBuffers compiler, do not modify
export { HelloReply } from './models/hello-reply';
export { HelloRequest } from './models/hello-request';
export { HelloReply } from './models/hello-reply.js';
export { HelloRequest } from './models/hello-request.js';

View File

@@ -65,4 +65,4 @@ class Allocator {
} // namespace flatbuffers
#endif // FLATBUFFERS_ALLOCATOR_H_
#endif // FLATBUFFERS_ALLOCATOR_H_

View File

@@ -17,6 +17,8 @@
#ifndef FLATBUFFERS_ARRAY_H_
#define FLATBUFFERS_ARRAY_H_
#include <memory>
#include "flatbuffers/base.h"
#include "flatbuffers/stl_emulation.h"
#include "flatbuffers/vector.h"
@@ -35,7 +37,7 @@ template<typename T, uint16_t length> class Array {
public:
typedef uint16_t size_type;
typedef typename IndirectHelper<IndirectHelperType>::return_type return_type;
typedef VectorIterator<T, return_type> const_iterator;
typedef VectorConstIterator<T, return_type> const_iterator;
typedef VectorReverseIterator<const_iterator> const_reverse_iterator;
// If T is a LE-scalar or a struct (!scalar_tag::value).
@@ -238,6 +240,14 @@ const Array<E, length> &CastToArrayOfEnum(const T (&arr)[length]) {
return *reinterpret_cast<const Array<E, length> *>(arr);
}
template<typename T, uint16_t length>
bool operator==(const Array<T, length> &lhs,
const Array<T, length> &rhs) noexcept {
return std::addressof(lhs) == std::addressof(rhs) ||
(lhs.size() == rhs.size() &&
std::memcmp(lhs.Data(), rhs.Data(), rhs.size() * sizeof(T)) == 0);
}
} // namespace flatbuffers
#endif // FLATBUFFERS_ARRAY_H_

View File

@@ -32,7 +32,7 @@
#include <cstdlib>
#include <cstring>
#if defined(ARDUINO) && !defined(ARDUINOSTL_M_H)
#if defined(ARDUINO) && !defined(ARDUINOSTL_M_H) && defined(__AVR__)
#include <utility.h>
#else
#include <utility>
@@ -138,9 +138,9 @@
#endif
#endif // !defined(FLATBUFFERS_LITTLEENDIAN)
#define FLATBUFFERS_VERSION_MAJOR 2
#define FLATBUFFERS_VERSION_MINOR 0
#define FLATBUFFERS_VERSION_REVISION 8
#define FLATBUFFERS_VERSION_MAJOR 23
#define FLATBUFFERS_VERSION_MINOR 1
#define FLATBUFFERS_VERSION_REVISION 20
#define FLATBUFFERS_STRING_EXPAND(X) #X
#define FLATBUFFERS_STRING(X) FLATBUFFERS_STRING_EXPAND(X)
namespace flatbuffers {

View File

@@ -17,6 +17,8 @@
#ifndef FLATBUFFERS_BUFFER_H_
#define FLATBUFFERS_BUFFER_H_
#include <algorithm>
#include "flatbuffers/base.h"
namespace flatbuffers {
@@ -76,6 +78,9 @@ template<typename T> struct IndirectHelper {
static return_type Read(const uint8_t *p, uoffset_t i) {
return EndianScalar((reinterpret_cast<const T *>(p))[i]);
}
static return_type Read(uint8_t *p, uoffset_t i) {
return Read(const_cast<const uint8_t *>(p), i);
}
};
template<typename T> struct IndirectHelper<Offset<T>> {
typedef const T *return_type;
@@ -85,13 +90,20 @@ template<typename T> struct IndirectHelper<Offset<T>> {
p += i * sizeof(uoffset_t);
return reinterpret_cast<return_type>(p + ReadScalar<uoffset_t>(p));
}
static mutable_return_type Read(uint8_t *p, uoffset_t i) {
p += i * sizeof(uoffset_t);
return reinterpret_cast<mutable_return_type>(p + ReadScalar<uoffset_t>(p));
}
};
template<typename T> struct IndirectHelper<const T *> {
typedef const T *return_type;
typedef T *mutable_return_type;
static const size_t element_stride = sizeof(T);
static return_type Read(const uint8_t *p, uoffset_t i) {
return reinterpret_cast<const T *>(p + i * sizeof(T));
return reinterpret_cast<return_type>(p + i * sizeof(T));
}
static mutable_return_type Read(uint8_t *p, uoffset_t i) {
return reinterpret_cast<mutable_return_type>(p + i * sizeof(T));
}
};
@@ -139,4 +151,4 @@ template<typename T> const T *GetSizePrefixedRoot(const void *buf) {
} // namespace flatbuffers
#endif // FLATBUFFERS_BUFFER_H_
#endif // FLATBUFFERS_BUFFER_H_

View File

@@ -50,4 +50,4 @@ template<typename T> struct BufferRef : BufferRefBase {
} // namespace flatbuffers
#endif // FLATBUFFERS_BUFFER_REF_H_
#endif // FLATBUFFERS_BUFFER_REF_H_

View File

@@ -0,0 +1,73 @@
/*
* Copyright 2023 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef FLATBUFFERS_CODE_GENERATOR_H_
#define FLATBUFFERS_CODE_GENERATOR_H_
#include <string>
#include "flatbuffers/idl.h"
namespace flatbuffers {
// An code generator interface for producing converting flatbuffer schema into
// code.
class CodeGenerator {
public:
virtual ~CodeGenerator() = default;
enum Status {
OK = 0,
ERROR = 1,
NOT_IMPLEMENTED = 2,
};
// Generate code from the provided `parser`.
//
// DEPRECATED: prefer using the other overload of GenerateCode for bfbs.
virtual Status GenerateCode(const Parser &parser, const std::string &path,
const std::string &filename) = 0;
// Generate code from the provided `buffer` of given `length`. The buffer is a
// serialized reflection.fbs.
virtual Status GenerateCode(const uint8_t *buffer, int64_t length) = 0;
virtual Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename,
std::string &output) = 0;
virtual Status GenerateGrpcCode(const Parser &parser, const std::string &path,
const std::string &filename) = 0;
virtual bool IsSchemaOnly() const = 0;
virtual bool SupportsBfbsGeneration() const = 0;
virtual IDLOptions::Language Language() const = 0;
virtual std::string LanguageName() const = 0;
protected:
CodeGenerator() = default;
private:
// Copying is not supported.
CodeGenerator(const CodeGenerator &) = delete;
CodeGenerator &operator=(const CodeGenerator &) = delete;
};
} // namespace flatbuffers
#endif // FLATBUFFERS_CODE_GENERATOR_H_

View File

@@ -61,4 +61,4 @@ inline uint8_t *ReallocateDownward(Allocator *allocator, uint8_t *old_p,
} // namespace flatbuffers
#endif // FLATBUFFERS_DEFAULT_ALLOCATOR_H_
#endif // FLATBUFFERS_DEFAULT_ALLOCATOR_H_

View File

@@ -45,7 +45,7 @@ class DetachedBuffer {
cur_(cur),
size_(sz) {}
DetachedBuffer(DetachedBuffer &&other)
DetachedBuffer(DetachedBuffer &&other) noexcept
: allocator_(other.allocator_),
own_allocator_(other.own_allocator_),
buf_(other.buf_),
@@ -55,7 +55,7 @@ class DetachedBuffer {
other.reset();
}
DetachedBuffer &operator=(DetachedBuffer &&other) {
DetachedBuffer &operator=(DetachedBuffer &&other) noexcept {
if (this == &other) return *this;
destroy();

View File

@@ -17,6 +17,7 @@
#ifndef FLATBUFFERS_FLATBUFFER_BUILDER_H_
#define FLATBUFFERS_FLATBUFFER_BUILDER_H_
#include <algorithm>
#include <functional>
#include <initializer_list>
@@ -97,7 +98,7 @@ class FlatBufferBuilder {
}
/// @brief Move constructor for FlatBufferBuilder.
FlatBufferBuilder(FlatBufferBuilder &&other)
FlatBufferBuilder(FlatBufferBuilder &&other) noexcept
: buf_(1024, nullptr, false, AlignOf<largest_scalar_t>()),
num_field_loc(0),
max_voffset_(0),
@@ -115,7 +116,7 @@ class FlatBufferBuilder {
}
/// @brief Move assignment operator for FlatBufferBuilder.
FlatBufferBuilder &operator=(FlatBufferBuilder &&other) {
FlatBufferBuilder &operator=(FlatBufferBuilder &&other) noexcept {
// Move construct a temporary and swap idiom
FlatBufferBuilder temp(std::move(other));
Swap(temp);
@@ -449,7 +450,7 @@ class FlatBufferBuilder {
}
template<typename T> void PreAlign(size_t len) {
AssertScalarT<T>();
PreAlign(len, sizeof(T));
PreAlign(len, AlignOf<T>());
}
/// @endcond
@@ -589,11 +590,15 @@ class FlatBufferBuilder {
return PushElement(static_cast<uoffset_t>(len));
}
void StartVector(size_t len, size_t elemsize) {
void StartVector(size_t len, size_t elemsize, size_t alignment) {
NotNested();
nested = true;
PreAlign<uoffset_t>(len * elemsize);
PreAlign(len * elemsize, elemsize); // Just in case elemsize > uoffset_t.
PreAlign(len * elemsize, alignment); // Just in case elemsize > uoffset_t.
}
template<typename T> void StartVector(size_t len) {
return StartVector(len, sizeof(T), AlignOf<T>());
}
// Call this right before StartVector/CreateVector if you want to force the
@@ -627,7 +632,7 @@ class FlatBufferBuilder {
// If this assert hits, you're specifying a template argument that is
// causing the wrong overload to be selected, remove it.
AssertScalarT<T>();
StartVector(len, sizeof(T));
StartVector<T>(len);
if (len == 0) { return Offset<Vector<T>>(EndVector(len)); }
// clang-format off
#if FLATBUFFERS_LITTLEENDIAN
@@ -668,7 +673,7 @@ class FlatBufferBuilder {
template<typename T>
Offset<Vector<Offset<T>>> CreateVector(const Offset<T> *v, size_t len) {
StartVector(len, sizeof(Offset<T>));
StartVector<Offset<T>>(len);
for (auto i = len; i > 0;) { PushElement(v[--i]); }
return Offset<Vector<Offset<T>>>(EndVector(len));
}
@@ -688,7 +693,7 @@ class FlatBufferBuilder {
// an array. Instead, read elements manually.
// Background: https://isocpp.org/blog/2012/11/on-vectorbool
Offset<Vector<uint8_t>> CreateVector(const std::vector<bool> &v) {
StartVector(v.size(), sizeof(uint8_t));
StartVector<uint8_t>(v.size());
for (auto i = v.size(); i > 0;) {
PushElement(static_cast<uint8_t>(v[--i]));
}
@@ -762,7 +767,7 @@ class FlatBufferBuilder {
for (auto it = begin; it != end; ++it) {
buf_.scratch_push_small(CreateString(*it));
}
StartVector(size, sizeof(Offset<String>));
StartVector<Offset<String>>(size);
for (auto i = 1; i <= size; i++) {
// Note we re-evaluate the buf location each iteration to account for any
// underlying buffer resizing that may occur.
@@ -782,7 +787,7 @@ class FlatBufferBuilder {
/// where the vector is stored.
template<typename T>
Offset<Vector<const T *>> CreateVectorOfStructs(const T *v, size_t len) {
StartVector(len * sizeof(T) / AlignOf<T>(), AlignOf<T>());
StartVector(len * sizeof(T) / AlignOf<T>(), sizeof(T), AlignOf<T>());
if (len > 0) {
PushBytes(reinterpret_cast<const uint8_t *>(v), sizeof(T) * len);
}
@@ -1025,9 +1030,9 @@ class FlatBufferBuilder {
/// written to at a later time to serialize the data into a `vector`
/// in the buffer.
uoffset_t CreateUninitializedVector(size_t len, size_t elemsize,
uint8_t **buf) {
size_t alignment, uint8_t **buf) {
NotNested();
StartVector(len, elemsize);
StartVector(len, elemsize, alignment);
buf_.make_space(len * elemsize);
auto vec_start = GetSize();
auto vec_end = EndVector(len);
@@ -1035,6 +1040,12 @@ class FlatBufferBuilder {
return vec_end;
}
FLATBUFFERS_ATTRIBUTE([[deprecated("call the version above instead")]])
uoffset_t CreateUninitializedVector(size_t len, size_t elemsize,
uint8_t **buf) {
return CreateUninitializedVector(len, elemsize, elemsize, buf);
}
/// @brief Specialized version of `CreateVector` for non-copying use cases.
/// Write the data any time later to the returned buffer pointer `buf`.
/// @tparam T The data type of the data that will be stored in the buffer
@@ -1046,14 +1057,14 @@ class FlatBufferBuilder {
template<typename T>
Offset<Vector<T>> CreateUninitializedVector(size_t len, T **buf) {
AssertScalarT<T>();
return CreateUninitializedVector(len, sizeof(T),
return CreateUninitializedVector(len, sizeof(T), AlignOf<T>(),
reinterpret_cast<uint8_t **>(buf));
}
template<typename T>
Offset<Vector<const T *>> CreateUninitializedVectorOfStructs(size_t len,
T **buf) {
return CreateUninitializedVector(len, sizeof(T),
return CreateUninitializedVector(len, sizeof(T), AlignOf<T>(),
reinterpret_cast<uint8_t **>(buf));
}
@@ -1064,7 +1075,7 @@ class FlatBufferBuilder {
Offset<Vector<T>> CreateVectorScalarCast(const U *v, size_t len) {
AssertScalarT<T>();
AssertScalarT<U>();
StartVector(len, sizeof(T));
StartVector<T>(len);
for (auto i = len; i > 0;) { PushElement(static_cast<T>(v[--i])); }
return Offset<Vector<T>>(EndVector(len));
}
@@ -1173,7 +1184,7 @@ class FlatBufferBuilder {
// Allocates space for a vector of structures.
// Must be completed with EndVectorOfStructs().
template<typename T> T *StartVectorOfStructs(size_t vector_size) {
StartVector(vector_size * sizeof(T) / AlignOf<T>(), AlignOf<T>());
StartVector(vector_size * sizeof(T) / AlignOf<T>(), sizeof(T), AlignOf<T>());
return reinterpret_cast<T *>(buf_.make_space(vector_size * sizeof(T)));
}

View File

@@ -17,6 +17,8 @@
#ifndef FLATBUFFERS_H_
#define FLATBUFFERS_H_
#include <algorithm>
// TODO: These includes are for mitigating the pains of users editing their
// source because they relied on flatbuffers.h to include everything for them.
#include "flatbuffers/array.h"

View File

@@ -19,18 +19,51 @@
#include <functional>
#include <limits>
#include <list>
#include <memory>
#include <string>
#include "flatbuffers/bfbs_generator.h"
#include "flatbuffers/code_generator.h"
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
namespace flatbuffers {
// TODO(derekbailey): It would be better to define these as normal includes and
// not as extern functions. But this can be done at a later time.
extern std::unique_ptr<flatbuffers::CodeGenerator> NewCppCodeGenerator();
extern void LogCompilerWarn(const std::string &warn);
extern void LogCompilerError(const std::string &err);
struct FlatCOptions {
IDLOptions opts;
std::string program_name;
std::string output_path;
std::vector<std::string> filenames;
std::list<std::string> include_directories_storage;
std::vector<const char *> include_directories;
std::vector<const char *> conform_include_directories;
std::vector<bool> generator_enabled;
size_t binary_files_from = std::numeric_limits<size_t>::max();
std::string conform_to_schema;
std::string annotate_schema;
bool any_generator = false;
bool print_make_rules = false;
bool raw_binary = false;
bool schema_binary = false;
bool grpc_enabled = false;
bool requires_bfbs = false;
std::vector<std::shared_ptr<CodeGenerator>> generators;
};
struct FlatCOption {
std::string short_opt;
std::string long_opt;
@@ -85,15 +118,21 @@ class FlatCompiler {
explicit FlatCompiler(const InitParams &params) : params_(params) {}
int Compile(int argc, const char **argv);
bool RegisterCodeGenerator(const std::string& flag,
std::shared_ptr<CodeGenerator> code_generator);
std::string GetShortUsageString(const char *program_name) const;
std::string GetUsageString(const char *program_name) const;
int Compile(const FlatCOptions &options);
std::string GetShortUsageString(const std::string &program_name) const;
std::string GetUsageString(const std::string &program_name) const;
// Parse the FlatC options from command line arguments.
FlatCOptions ParseFromCommandLineArguments(int argc, const char **argv);
private:
void ParseFile(flatbuffers::Parser &parser, const std::string &filename,
const std::string &contents,
std::vector<const char *> &include_directories) const;
const std::vector<const char *> &include_directories) const;
void LoadBinarySchema(Parser &parser, const std::string &filename,
const std::string &contents);
@@ -105,9 +144,18 @@ class FlatCompiler {
void AnnotateBinaries(const uint8_t *binary_schema,
uint64_t binary_schema_size,
const std::string & schema_filename,
const std::string &schema_filename,
const std::vector<std::string> &binary_files);
void ValidateOptions(const FlatCOptions &options);
Parser GetConformParser(const FlatCOptions &options);
std::unique_ptr<Parser> GenerateCode(const FlatCOptions &options,
Parser &conform_parser);
std::map<std::string, std::shared_ptr<CodeGenerator>> code_generators_;
InitParams params_;
};

View File

@@ -17,6 +17,7 @@
#ifndef FLATBUFFERS_FLEXBUFFERS_H_
#define FLATBUFFERS_FLEXBUFFERS_H_
#include <algorithm>
#include <map>
// Used to select STL variant.
#include "flatbuffers/base.h"
@@ -382,10 +383,10 @@ class Reference {
type_(type) {}
Reference(const uint8_t *data, uint8_t parent_width, uint8_t packed_type)
: data_(data), parent_width_(parent_width) {
byte_width_ = 1U << static_cast<BitWidth>(packed_type & 3);
type_ = static_cast<Type>(packed_type >> 2);
}
: data_(data),
parent_width_(parent_width),
byte_width_(static_cast<uint8_t>(1 << (packed_type & 3))),
type_(static_cast<Type>(packed_type >> 2)) {}
Type GetType() const { return type_; }
@@ -1844,7 +1845,7 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
uint8_t len = 0;
auto vtype = ToFixedTypedVectorElementType(r.type_, &len);
if (!VerifyType(vtype)) return false;
return VerifyFromPointer(p, r.byte_width_ * len);
return VerifyFromPointer(p, static_cast<size_t>(r.byte_width_) * len);
}
default: return false;
}

View File

@@ -17,6 +17,7 @@
#ifndef FLATBUFFERS_IDL_H_
#define FLATBUFFERS_IDL_H_
#include <algorithm>
#include <functional>
#include <map>
#include <memory>
@@ -296,7 +297,8 @@ struct FieldDef : public Definition {
flexbuffer(false),
presence(kDefault),
nested_flatbuffer(nullptr),
padding(0) {}
padding(0),
sibling_union_field(nullptr) {}
Offset<reflection::Field> Serialize(FlatBufferBuilder *builder, uint16_t id,
const Parser &parser) const;
@@ -341,6 +343,12 @@ struct FieldDef : public Definition {
StructDef *nested_flatbuffer; // This field contains nested FlatBuffer data.
size_t padding; // Bytes to always pad after this field.
// sibling_union_field is always set to nullptr. The only exception is
// when FieldDef is a union field or an union type field. Therefore,
// sibling_union_field on a union field points to the union type field
// and vice-versa.
FieldDef *sibling_union_field;
};
struct StructDef : public Definition {
@@ -382,7 +390,14 @@ struct EnumVal {
Offset<reflection::EnumVal> Serialize(FlatBufferBuilder *builder,
const Parser &parser) const;
bool Deserialize(const Parser &parser, const reflection::EnumVal *val);
bool Deserialize(Parser &parser, const reflection::EnumVal *val);
flatbuffers::Offset<
flatbuffers::Vector<flatbuffers::Offset<reflection::KeyValue>>>
SerializeAttributes(FlatBufferBuilder *builder, const Parser &parser) const;
bool DeserializeAttributes(Parser &parser,
const Vector<Offset<reflection::KeyValue>> *attrs);
uint64_t GetAsUInt64() const { return static_cast<uint64_t>(value); }
int64_t GetAsInt64() const { return value; }
@@ -392,6 +407,7 @@ struct EnumVal {
std::string name;
std::vector<std::string> doc_comment;
Type union_type;
SymbolTable<Value> attributes;
private:
friend EnumDef;
@@ -464,6 +480,10 @@ inline bool IsStruct(const Type &type) {
return type.base_type == BASE_TYPE_STRUCT && type.struct_def->fixed;
}
inline bool IsIncompleteStruct(const Type &type) {
return type.base_type == BASE_TYPE_STRUCT && type.struct_def->predecl;
}
inline bool IsTable(const Type &type) {
return type.base_type == BASE_TYPE_STRUCT && !type.struct_def->fixed;
}
@@ -480,11 +500,11 @@ inline bool IsVector(const Type &type) {
return type.base_type == BASE_TYPE_VECTOR;
}
inline bool IsVectorOfStruct(const Type& type) {
inline bool IsVectorOfStruct(const Type &type) {
return IsVector(type) && IsStruct(type.VectorType());
}
inline bool IsVectorOfTable(const Type& type) {
inline bool IsVectorOfTable(const Type &type) {
return IsVector(type) && IsTable(type.VectorType());
}
@@ -528,8 +548,11 @@ inline bool operator!=(const EnumVal &lhs, const EnumVal &rhs) {
inline bool EqualByName(const Type &a, const Type &b) {
return a.base_type == b.base_type && a.element == b.element &&
(a.struct_def == b.struct_def ||
a.struct_def->name == b.struct_def->name) &&
(a.enum_def == b.enum_def || a.enum_def->name == b.enum_def->name);
(a.struct_def != nullptr && b.struct_def != nullptr &&
a.struct_def->name == b.struct_def->name)) &&
(a.enum_def == b.enum_def ||
(a.enum_def != nullptr && b.enum_def != nullptr &&
a.enum_def->name == b.enum_def->name));
}
struct RPCCall : public Definition {
@@ -578,9 +601,11 @@ struct IDLOptions {
bool strict_json;
bool output_default_scalars_in_json;
int indent_step;
bool cpp_minify_enums;
bool output_enum_identifiers;
bool prefixed_enums;
bool scoped_enums;
bool emit_min_max_enum_values;
bool swift_implementation_only;
bool include_dependence_headers;
bool mutable_buffer;
@@ -613,6 +638,7 @@ struct IDLOptions {
bool binary_schema_gen_embed;
std::string go_import;
std::string go_namespace;
std::string go_module_name;
bool protobuf_ascii_alike;
bool size_prefixed;
std::string root_type;
@@ -633,7 +659,9 @@ struct IDLOptions {
bool json_nested_flexbuffers;
bool json_nested_legacy_flatbuffers;
bool ts_flat_file;
bool ts_no_import_ext;
bool no_leak_private_annotations;
bool require_json_eof;
// Possible options for the more general generator below.
enum Language {
@@ -653,6 +681,7 @@ struct IDLOptions {
kRust = 1 << 14,
kKotlin = 1 << 15,
kSwift = 1 << 16,
kNim = 1 << 17,
kMAX
};
@@ -687,9 +716,11 @@ struct IDLOptions {
strict_json(false),
output_default_scalars_in_json(false),
indent_step(2),
cpp_minify_enums(false),
output_enum_identifiers(true),
prefixed_enums(true),
scoped_enums(false),
emit_min_max_enum_values(true),
swift_implementation_only(false),
include_dependence_headers(true),
mutable_buffer(false),
@@ -733,7 +764,9 @@ struct IDLOptions {
json_nested_flexbuffers(true),
json_nested_legacy_flatbuffers(false),
ts_flat_file(false),
ts_no_import_ext(false),
no_leak_private_annotations(false),
require_json_eof(true),
mini_reflect(IDLOptions::kNone),
require_explicit_ids(false),
rust_serialize(false),
@@ -746,7 +779,8 @@ struct IDLOptions {
// This encapsulates where the parser is in the current source file.
struct ParserState {
ParserState()
: cursor_(nullptr),
: prev_cursor_(nullptr),
cursor_(nullptr),
line_start_(nullptr),
line_(0),
token_(-1),
@@ -754,6 +788,7 @@ struct ParserState {
protected:
void ResetState(const char *source) {
prev_cursor_ = source;
cursor_ = source;
line_ = 0;
MarkNewLine();
@@ -769,6 +804,7 @@ struct ParserState {
return static_cast<int64_t>(cursor_ - line_start_);
}
const char *prev_cursor_;
const char *cursor_;
const char *line_start_;
int line_; // the current line being parsed
@@ -874,6 +910,13 @@ class Parser : public ParserState {
known_attributes_["private"] = true;
}
// Copying is not allowed
Parser(const Parser &) = delete;
Parser &operator=(const Parser &) = delete;
Parser(Parser &&) = default;
Parser &operator=(Parser &&) = default;
~Parser() {
for (auto it = namespaces_.begin(); it != namespaces_.end(); ++it) {
delete *it;
@@ -896,6 +939,9 @@ class Parser : public ParserState {
bool ParseJson(const char *json, const char *json_filename = nullptr);
// Returns the number of characters were consumed when parsing a JSON string.
std::ptrdiff_t BytesConsumed() const;
// Set the root type. May override the one set in the schema.
bool SetRootType(const char *name);
@@ -1016,6 +1062,7 @@ class Parser : public ParserState {
FLATBUFFERS_CHECKED_ERROR ParseService(const char *filename);
FLATBUFFERS_CHECKED_ERROR ParseProtoFields(StructDef *struct_def,
bool isextend, bool inside_oneof);
FLATBUFFERS_CHECKED_ERROR ParseProtoMapField(StructDef *struct_def);
FLATBUFFERS_CHECKED_ERROR ParseProtoOption();
FLATBUFFERS_CHECKED_ERROR ParseProtoKey();
FLATBUFFERS_CHECKED_ERROR ParseProtoDecl();

View File

@@ -407,8 +407,9 @@ struct ToStringVisitor : public IterationVisitor {
inline std::string FlatBufferToString(const uint8_t *buffer,
const TypeTable *type_table,
bool multi_line = false,
bool vector_delimited = true) {
ToStringVisitor tostring_visitor(multi_line ? "\n" : " ", false, "",
bool vector_delimited = true,
const std::string& indent = "") {
ToStringVisitor tostring_visitor(multi_line ? "\n" : " ", false, indent,
vector_delimited);
IterateFlatBuffer(buffer, type_table, &tostring_visitor);
return tostring_visitor.s;

File diff suppressed because it is too large Load Diff

View File

@@ -61,4 +61,4 @@ static inline flatbuffers::string_view GetStringView(const String *str) {
} // namespace flatbuffers
#endif // FLATBUFFERS_STRING_H_
#endif // FLATBUFFERS_STRING_H_

View File

@@ -50,4 +50,4 @@ class Struct FLATBUFFERS_FINAL_CLASS {
} // namespace flatbuffers
#endif // FLATBUFFERS_STRUCT_H_
#endif // FLATBUFFERS_STRUCT_H_

View File

@@ -31,6 +31,8 @@
# include <stdio.h>
#endif // FLATBUFFERS_PREFER_PRINTF
#include <cmath>
#include <limits>
#include <string>
namespace flatbuffers {
@@ -312,6 +314,7 @@ inline bool StringToFloatImpl(T *val, const char *const str) {
strtoval_impl(val, str, const_cast<char **>(&end));
auto done = (end != str) && (*end == '\0');
if (!done) *val = 0; // erase partial result
if (done && std::isnan(*val)) { *val = std::numeric_limits<T>::quiet_NaN(); }
return done;
}
@@ -392,6 +395,18 @@ inline uint64_t StringToUInt(const char *s, int base = 10) {
return StringToIntegerImpl(&val, s, base) ? val : 0;
}
inline bool StringIsFlatbufferNan(const std::string &s) {
return s == "nan" || s == "+nan" || s == "-nan";
}
inline bool StringIsFlatbufferPositiveInfinity(const std::string &s) {
return s == "inf" || s == "+inf" || s == "infinity" || s == "+infinity";
}
inline bool StringIsFlatbufferNegativeInfinity(const std::string &s) {
return s == "-inf" || s == "-infinity";
}
typedef bool (*LoadFileFunction)(const char *filename, bool binary,
std::string *dest);
typedef bool (*FileExistsFunction)(const char *filename);
@@ -685,9 +700,6 @@ bool SetGlobalTestLocale(const char *locale_name,
bool ReadEnvironmentVariable(const char *var_name,
std::string *_value = nullptr);
// MSVC specific: Send all assert reports to STDOUT to prevent CI hangs.
void SetupDefaultCRTReportMode();
enum class Case {
kUnknown = 0,
// TheQuickBrownFox

View File

@@ -27,14 +27,15 @@ struct String;
// An STL compatible iterator implementation for Vector below, effectively
// calling Get() for every element.
template<typename T, typename IT> struct VectorIterator {
template<typename T, typename IT, typename Data = uint8_t *>
struct VectorIterator {
typedef std::random_access_iterator_tag iterator_category;
typedef IT value_type;
typedef ptrdiff_t difference_type;
typedef IT *pointer;
typedef IT &reference;
VectorIterator(const uint8_t *data, uoffset_t i)
VectorIterator(Data data, uoffset_t i)
: data_(data + IndirectHelper<T>::element_stride * i) {}
VectorIterator(const VectorIterator &other) : data_(other.data_) {}
VectorIterator() : data_(nullptr) {}
@@ -116,9 +117,12 @@ template<typename T, typename IT> struct VectorIterator {
}
private:
const uint8_t *data_;
Data data_;
};
template<typename T, typename IT>
using VectorConstIterator = VectorIterator<T, IT, const uint8_t *>;
template<typename Iterator>
struct VectorReverseIterator : public std::reverse_iterator<Iterator> {
explicit VectorReverseIterator(Iterator iter)
@@ -145,7 +149,7 @@ template<typename T> class Vector {
public:
typedef VectorIterator<T, typename IndirectHelper<T>::mutable_return_type>
iterator;
typedef VectorIterator<T, typename IndirectHelper<T>::return_type>
typedef VectorConstIterator<T, typename IndirectHelper<T>::return_type>
const_iterator;
typedef VectorReverseIterator<iterator> reverse_iterator;
typedef VectorReverseIterator<const_iterator> const_reverse_iterator;

View File

@@ -17,6 +17,8 @@
#ifndef FLATBUFFERS_VECTOR_DOWNWARD_H_
#define FLATBUFFERS_VECTOR_DOWNWARD_H_
#include <algorithm>
#include "flatbuffers/base.h"
#include "flatbuffers/default_allocator.h"
#include "flatbuffers/detached_buffer.h"
@@ -43,7 +45,7 @@ class vector_downward {
cur_(nullptr),
scratch_(nullptr) {}
vector_downward(vector_downward &&other)
vector_downward(vector_downward &&other) noexcept
// clang-format on
: allocator_(other.allocator_),
own_allocator_(other.own_allocator_),
@@ -64,7 +66,7 @@ class vector_downward {
other.scratch_ = nullptr;
}
vector_downward &operator=(vector_downward &&other) {
vector_downward &operator=(vector_downward &&other) noexcept {
// Move construct a temporary and swap idiom
vector_downward temp(std::move(other));
swap(temp);

View File

@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.google.flatbuffers</groupId>
<artifactId>flatbuffers-java</artifactId>
<version>2.0.8</version>
<version>23.1.4</version>
<packaging>bundle</packaging>
<name>FlatBuffers Java API</name>
<description>
@@ -37,6 +37,18 @@
<tag>HEAD</tag>
</scm>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.truth</groupId>
<artifactId>truth</artifactId>
<version>1.1.3</version>
<scope>test</scope>
</dependency>
</dependencies>
<distributionManagement>
<snapshotRepository>
@@ -45,7 +57,19 @@
</snapshotRepository>
</distributionManagement>
<build>
<sourceDirectory>java</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<release>8</release>
<testExcludes>
<testExclude>MyGame/Example/MonsterStorageGrpc.java</testExclude>
<testExclude>MyGame/OtherNameSpace/TableBT.java</testExclude>
</testExcludes>
</configuration>
<version>3.8.1</version>
</plugin>
</plugins>
</build>
<profiles>
<profile>
@@ -55,13 +79,6 @@
</activation>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<release>8</release>
</configuration>
<version>3.8.1</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
@@ -130,10 +147,10 @@
<goal>sign</goal>
</goals>
<configuration>
<gpgArguments>
<arg>--pinentry-mode</arg>
<arg>loopback</arg>
</gpgArguments>
<gpgArguments>
<arg>--pinentry-mode</arg>
<arg>loopback</arg>
</gpgArguments>
</configuration>
</execution>
</executions>
@@ -154,4 +171,3 @@
</profile>
</profiles>
</project>

View File

@@ -46,7 +46,7 @@ public class Constants {
Changes to the Java implementation need to be sure to change
the version here and in the code generator on every possible
incompatible change */
public static void FLATBUFFERS_2_0_8() {}
public static void FLATBUFFERS_23_1_20() {}
}
/// @endcond

View File

@@ -173,6 +173,21 @@ public class FlexBuffersBuilder {
return bb;
}
/**
* Insert a null value into the buffer
*/
public void putNull() {
putNull(null);
}
/**
* Insert a null value into the buffer
* @param key key used to store element in map
*/
public void putNull(String key) {
stack.add(Value.nullValue(putKey(key)));
}
/**
* Insert a single boolean into the buffer
* @param val true or false
@@ -502,7 +517,9 @@ public class FlexBuffersBuilder {
* @return Value representing the created vector
*/
private Value createVector(int key, int start, int length, boolean typed, boolean fixed, Value keys) {
assert (!fixed || typed); // typed=false, fixed=true combination is not supported.
if (fixed & !typed)
throw new UnsupportedOperationException("Untyped fixed vector is not supported");
// Figure out smallest bit width we can store this vector with.
int bitWidth = Math.max(WIDTH_8, widthUInBits(length));
int prefixElems = 1;
@@ -673,6 +690,10 @@ public class FlexBuffersBuilder {
this.iValue = Long.MIN_VALUE;
}
static Value nullValue(int key) {
return new Value(key, FBT_NULL, WIDTH_8, 0);
}
static Value bool(int key, boolean b) {
return new Value(key, FBT_BOOL, WIDTH_8, b ? 1 : 0);
}

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