Compare commits

..

52 Commits

Author SHA1 Message Date
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
309 changed files with 16035 additions and 6918 deletions

View File

@@ -367,7 +367,7 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v2
- uses: gradle/wrapper-validation-action@v1
- uses: gradle/wrapper-validation-action@v1.0.5
- uses: actions/setup-java@v2
with:
distribution: 'adopt-hotspot'
@@ -386,11 +386,11 @@ jobs:
with:
distribution: 'adopt-hotspot'
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
@@ -431,7 +431,9 @@ jobs:
- uses: actions/checkout@v2
- name: test
working-directory: tests/swift/tests
run: sh SwiftTest.sh
run: |
swift build --build-tests
swift test
build-swift-wasm:
name: Build Swift Wasm
@@ -524,7 +526,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

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 }}

1
.gitignore vendored
View File

@@ -149,4 +149,5 @@ flatbuffers.pc
**/html/**
**/latex/**
# https://cmake.org/cmake/help/latest/module/FetchContent.html#variable:FETCHCONTENT_BASE_DIR
cmake-build-debug/
_deps/

View File

@@ -1,37 +1,39 @@
set(VERSION_MAJOR 22)
set(VERSION_MINOR 10)
set(VERSION_PATCH 25)
set(VERSION_MINOR 11)
set(VERSION_PATCH 22)
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
@@ -219,6 +226,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
@@ -257,6 +265,8 @@ set(FlatBuffers_Tests_SRCS
${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
@@ -358,8 +368,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
@@ -375,7 +385,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
@@ -407,8 +417,8 @@ else()
-Wno-error=stringop-overflow
>
>
-pedantic
-Wextra
-pedantic
-Wextra
-Wno-unused-parameter
-Wold-style-cast
-fsigned-char
@@ -422,7 +432,7 @@ else()
$<$<VERSION_GREATER:$<CXX_COMPILER_VERSION>,3.8>:
-Wimplicit-fallthrough
-Wextra-semi
$<$<BOOL:${FLATBUFFERS_STRICT_MODE}>:
$<$<BOOL:${FLATBUFFERS_STRICT_MODE}>:
-Werror=unused-private-field
>
>
@@ -431,7 +441,7 @@ else()
$<$<CXX_COMPILER_ID:GNU>:
$<$<VERSION_GREATER:$<CXX_COMPILER_VERSION>,4.4>:
-Wunused-result
-Wunused-parameter
-Wunused-parameter
-Werror=unused-parameter
-Wmissing-declarations
>
@@ -439,7 +449,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
>
@@ -469,7 +479,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>
)
@@ -487,7 +497,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
@@ -578,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}"
@@ -630,6 +640,7 @@ if(FLATBUFFERS_BUILD_TESTS)
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()
@@ -689,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()
@@ -708,8 +719,8 @@ if(FLATBUFFERS_INSTALL)
configure_file(CMake/flatbuffers-config-version.cmake.in flatbuffers-config-version.cmake @ONLY)
install(
FILES
"CMake/flatbuffers-config.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 = '22.10.25'
s.version = '22.11.22'
s.summary = 'FlatBuffers: Memory Efficient Serialization Library'
s.description = "FlatBuffers is a cross platform serialization library architected for

View File

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

View File

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

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

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

@@ -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,62 @@
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))
// Encode builder head in last 4 bytes of request body
buf := make([]byte, 4)
flatbuffers.WriteUOffsetT(buf, b.Head())
buf = append(b.Bytes, buf...)
return bytes.NewReader(buf)
}
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
}
// Last 4 bytes is offset.
off := flatbuffers.GetUOffsetT(body[len(body)-4:])
buf := body[:len(body) - 4]
res := net.GetRootAsResponse(buf, off)
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,35 @@
package main
import (
"echo/net"
"fmt"
"io/ioutil"
"net/http"
flatbuffers "github.com/google/flatbuffers/go"
)
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
}
// Last 4 bytes is offset. See client.go.
off := flatbuffers.GetUOffsetT(body[len(body)-4:])
buf := body[:len(body) - 4]
req := net.GetRootAsRequest(buf, off)
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

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

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>
@@ -139,8 +139,8 @@
#endif // !defined(FLATBUFFERS_LITTLEENDIAN)
#define FLATBUFFERS_VERSION_MAJOR 22
#define FLATBUFFERS_VERSION_MINOR 10
#define FLATBUFFERS_VERSION_REVISION 25
#define FLATBUFFERS_VERSION_MINOR 11
#define FLATBUFFERS_VERSION_REVISION 22
#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 {
@@ -149,4 +151,4 @@ template<typename T> const T *GetSizePrefixedRoot(const void *buf) {
} // namespace flatbuffers
#endif // FLATBUFFERS_BUFFER_H_
#endif // FLATBUFFERS_BUFFER_H_

View File

@@ -17,6 +17,7 @@
#ifndef FLATBUFFERS_FLATBUFFER_BUILDER_H_
#define FLATBUFFERS_FLATBUFFER_BUILDER_H_
#include <algorithm>
#include <functional>
#include <initializer_list>

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

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

View File

@@ -17,6 +17,7 @@
#ifndef FLATBUFFERS_IDL_H_
#define FLATBUFFERS_IDL_H_
#include <algorithm>
#include <functional>
#include <map>
#include <memory>
@@ -488,11 +489,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());
}
@@ -586,6 +587,7 @@ 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;
@@ -621,6 +623,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;
@@ -642,6 +645,7 @@ struct IDLOptions {
bool json_nested_legacy_flatbuffers;
bool ts_flat_file;
bool no_leak_private_annotations;
bool require_json_eof;
// Possible options for the more general generator below.
enum Language {
@@ -696,6 +700,7 @@ 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),
@@ -743,6 +748,7 @@ struct IDLOptions {
json_nested_legacy_flatbuffers(false),
ts_flat_file(false),
no_leak_private_annotations(false),
require_json_eof(true),
mini_reflect(IDLOptions::kNone),
require_explicit_ids(false),
rust_serialize(false),
@@ -755,7 +761,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),
@@ -763,6 +770,7 @@ struct ParserState {
protected:
void ResetState(const char *source) {
prev_cursor_ = source;
cursor_ = source;
line_ = 0;
MarkNewLine();
@@ -777,7 +785,8 @@ struct ParserState {
FLATBUFFERS_ASSERT(cursor_ && line_start_ && cursor_ >= line_start_);
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
@@ -905,6 +914,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);
@@ -1025,6 +1037,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;

View File

@@ -9,8 +9,8 @@
// 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 == 22 &&
FLATBUFFERS_VERSION_MINOR == 10 &&
FLATBUFFERS_VERSION_REVISION == 25,
FLATBUFFERS_VERSION_MINOR == 11 &&
FLATBUFFERS_VERSION_REVISION == 22,
"Non-compatible flatbuffers version included");
namespace reflection {
@@ -265,7 +265,7 @@ struct KeyValue FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
const flatbuffers::String *key() const {
return GetPointer<const flatbuffers::String *>(VT_KEY);
}
bool KeyCompareLessThan(const KeyValue *o) const {
bool KeyCompareLessThan(const KeyValue * const o) const {
return *key() < *o->key();
}
int KeyCompareWithValue(const char *_key) const {
@@ -343,7 +343,7 @@ struct EnumVal FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
int64_t value() const {
return GetField<int64_t>(VT_VALUE, 0);
}
bool KeyCompareLessThan(const EnumVal *o) const {
bool KeyCompareLessThan(const EnumVal * const o) const {
return value() < o->value();
}
int KeyCompareWithValue(int64_t _value) const {
@@ -455,7 +455,7 @@ struct Enum FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
const flatbuffers::String *name() const {
return GetPointer<const flatbuffers::String *>(VT_NAME);
}
bool KeyCompareLessThan(const Enum *o) const {
bool KeyCompareLessThan(const Enum * const o) const {
return *name() < *o->name();
}
int KeyCompareWithValue(const char *_name) const {
@@ -606,7 +606,7 @@ struct Field FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
const flatbuffers::String *name() const {
return GetPointer<const flatbuffers::String *>(VT_NAME);
}
bool KeyCompareLessThan(const Field *o) const {
bool KeyCompareLessThan(const Field * const o) const {
return *name() < *o->name();
}
int KeyCompareWithValue(const char *_name) const {
@@ -812,7 +812,7 @@ struct Object FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
const flatbuffers::String *name() const {
return GetPointer<const flatbuffers::String *>(VT_NAME);
}
bool KeyCompareLessThan(const Object *o) const {
bool KeyCompareLessThan(const Object * const o) const {
return *name() < *o->name();
}
int KeyCompareWithValue(const char *_name) const {
@@ -964,7 +964,7 @@ struct RPCCall FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
const flatbuffers::String *name() const {
return GetPointer<const flatbuffers::String *>(VT_NAME);
}
bool KeyCompareLessThan(const RPCCall *o) const {
bool KeyCompareLessThan(const RPCCall * const o) const {
return *name() < *o->name();
}
int KeyCompareWithValue(const char *_name) const {
@@ -1080,7 +1080,7 @@ struct Service FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
const flatbuffers::String *name() const {
return GetPointer<const flatbuffers::String *>(VT_NAME);
}
bool KeyCompareLessThan(const Service *o) const {
bool KeyCompareLessThan(const Service * const o) const {
return *name() < *o->name();
}
int KeyCompareWithValue(const char *_name) const {
@@ -1199,7 +1199,7 @@ struct SchemaFile FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
const flatbuffers::String *filename() const {
return GetPointer<const flatbuffers::String *>(VT_FILENAME);
}
bool KeyCompareLessThan(const SchemaFile *o) const {
bool KeyCompareLessThan(const SchemaFile * const o) const {
return *filename() < *o->filename();
}
int KeyCompareWithValue(const char *_filename) const {

View File

@@ -31,6 +31,7 @@
# include <stdio.h>
#endif // FLATBUFFERS_PREFER_PRINTF
#include <limits>
#include <string>
namespace flatbuffers {
@@ -392,6 +393,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);

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"

View File

@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.google.flatbuffers</groupId>
<artifactId>flatbuffers-java</artifactId>
<version>22.10.25</version>
<version>22.11.22</version>
<packaging>bundle</packaging>
<name>FlatBuffers Java API</name>
<description>

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_22_10_25() {}
public static void FLATBUFFERS_22_11_22() {}
}
/// @endcond

View File

@@ -32,6 +32,6 @@ namespace Google.FlatBuffers
Changes to the C# implementation need to be sure to change
the version here and in the code generator on every possible
incompatible change */
public static void FLATBUFFERS_22_10_25() {}
public static void FLATBUFFERS_22_11_22() {}
}
}

View File

@@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFrameworks>netstandard2.1;netstandard2.0;net46</TargetFrameworks>
<Description>A cross-platform memory efficient serialization library</Description>
<PackageVersion>22.10.25</PackageVersion>
<PackageVersion>22.11.22</PackageVersion>
<Authors>Google LLC</Authors>
<PackageProjectUrl>https://github.com/google/flatbuffers</PackageProjectUrl>
<RepositoryUrl>https://github.com/google/flatbuffers</RepositoryUrl>

View File

@@ -1,6 +1,6 @@
{
"name": "flatbuffers",
"version": "22.10.25",
"version": "22.11.22",
"description": "Memory Efficient Serialization Library",
"files": [
"js/**/*.js",

View File

@@ -14,4 +14,4 @@
# Placeholder, to be updated during the release process
# by the setup.py
__version__ = u"22.10.25"
__version__ = u"22.11.22"

View File

@@ -112,7 +112,8 @@ class Builder(object):
## @cond FLATBUFFERS_INTENRAL
__slots__ = ("Bytes", "current_vtable", "head", "minalign", "objectEnd",
"vtables", "nested", "forceDefaults", "finished", "vectorNumElems")
"vtables", "nested", "forceDefaults", "finished", "vectorNumElems",
"sharedStrings")
"""Maximum buffer size constant, in bytes.
@@ -141,6 +142,7 @@ class Builder(object):
self.vtables = {}
self.nested = False
self.forceDefaults = False
self.sharedStrings = {}
## @endcond
self.finished = False
@@ -405,6 +407,20 @@ class Builder(object):
self.vectorNumElems = None
return self.Offset()
def CreateSharedString(self, s, encoding='utf-8', errors='strict'):
"""
CreateSharedString checks if the string is already written to the buffer
before calling CreateString.
"""
if s in self.sharedStrings:
return self.sharedStrings[s]
off = self.CreateString(s, encoding, errors)
self.sharedStrings[s] = off
return off
def CreateString(self, s, encoding='utf-8', errors='strict'):
"""CreateString writes a null-terminated byte string as a vector."""

View File

@@ -12,54 +12,14 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import fileinput
import os
import re
import sys
from datetime import datetime
from setuptools import setup
def _update_version_attr(new_version):
for line in fileinput.input('flatbuffers/_version.py', inplace=True):
if line.startswith('__version__'):
line = re.sub(r'".*"', '"{}"'.format(new_version), line)
sys.stdout.write(line)
def version():
version = os.getenv('VERSION', None)
if version:
# Most git tags are prefixed with 'v' (example: v1.2.3) this is
# never desirable for artifact repositories, so we strip the
# leading 'v' if it's present.
version = version[1:] if version.startswith('v') else version
else:
# Default version is an ISO8601 compiliant datetime. PyPI doesn't allow
# the colon ':' character in its versions, and time is required to allow
# for multiple publications to master in one day. This datetime string
# uses the "basic" ISO8601 format for both its date and time components
# to avoid issues with the colon character (ISO requires that date and
# time components of a date-time string must be uniformly basic or
# extended, which is why the date component does not have dashes.
#
# Publications using datetime versions should only be made from master
# to represent the HEAD moving forward.
version = datetime.utcnow().strftime('%Y%m%d%H%M%S')
print("VERSION environment variable not set, using datetime instead: {}"
.format(version))
_update_version_attr(version)
return version
setup(
name='flatbuffers',
version=version(),
version='22.11.22',
license='Apache 2.0',
author='FlatBuffers Contributors',
author_email='me@rwinslow.com',
author='Derek Bailey',
author_email='derekbailey@google.com',
url='https://google.github.io/flatbuffers/',
long_description=('Python runtime library for use with the '
'`Flatbuffers <https://google.github.io/flatbuffers/>`_ '
@@ -81,4 +41,4 @@ setup(
'Documentation': 'https://google.github.io/flatbuffers/',
'Source': 'https://github.com/google/flatbuffers',
},
)
)

View File

@@ -17,7 +17,7 @@ maximum memory efficiency. It allows you to directly access serialized data with
## Supported operating systems
* Windows
* MacOS X
* macOS
* Linux
* Android
* And any others with a recent C++ compiler (C++ 11 and newer)

View File

@@ -1,6 +1,6 @@
[package]
name = "flatbuffers"
version = "22.9.29"
version = "22.10.26"
edition = "2018"
authors = ["Robert Winslow <hello@rwinslow.com>", "FlatBuffers Maintainers"]
license = "Apache-2.0"

Binary file not shown.

View File

@@ -9,8 +9,8 @@
// 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 == 22 &&
FLATBUFFERS_VERSION_MINOR == 10 &&
FLATBUFFERS_VERSION_REVISION == 25,
FLATBUFFERS_VERSION_MINOR == 11 &&
FLATBUFFERS_VERSION_REVISION == 22,
"Non-compatible flatbuffers version included");
namespace MyGame {

View File

@@ -31,7 +31,7 @@ public enum MyGame_Sample_Equipment: UInt8, Enum {
public struct MyGame_Sample_Vec3: NativeStruct {
static func validateVersion() { FlatBuffersVersion_22_10_25() }
static func validateVersion() { FlatBuffersVersion_22_11_22() }
private var _x: Float32
private var _y: Float32
@@ -56,7 +56,7 @@ public struct MyGame_Sample_Vec3: NativeStruct {
public struct MyGame_Sample_Vec3_Mutable: FlatBufferObject {
static func validateVersion() { FlatBuffersVersion_22_10_25() }
static func validateVersion() { FlatBuffersVersion_22_11_22() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Struct
@@ -72,7 +72,7 @@ public struct MyGame_Sample_Vec3_Mutable: FlatBufferObject {
public struct MyGame_Sample_Monster: FlatBufferObject {
static func validateVersion() { FlatBuffersVersion_22_10_25() }
static func validateVersion() { FlatBuffersVersion_22_11_22() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table
@@ -162,7 +162,7 @@ public struct MyGame_Sample_Monster: FlatBufferObject {
public struct MyGame_Sample_Weapon: FlatBufferObject {
static func validateVersion() { FlatBuffersVersion_22_10_25() }
static func validateVersion() { FlatBuffersVersion_22_11_22() }
public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table

View File

@@ -147,7 +147,7 @@ TS_OPTS = ["--ts", "--gen-name-strings"]
LOBSTER_OPTS = ["--lobster"]
SWIFT_OPTS = ["--swift", "--gen-json-emit", "--bfbs-filenames", str(tests_path)]
SWIFT_OPTS_CODE_GEN = [
"--swift",
"--swift",
"--gen-json-emit",
"--bfbs-filenames",
swift_code_gen
@@ -179,6 +179,20 @@ flatc(
data="monsterdata_test.json",
)
flatc(
NO_INCL_OPTS
+ DART_OPTS,
schema="include_test/include_test1.fbs",
include="include_test/sub",
)
flatc(
NO_INCL_OPTS
+ DART_OPTS,
schema="include_test/sub/include_test2.fbs",
include="include_test",
)
flatc(
NO_INCL_OPTS
+ TS_OPTS,
@@ -305,14 +319,14 @@ flatc(
# Generate the annotated binary of the monster_test binary schema.
flatc_annotate(
schema="../reflection/reflection.fbs",
file="monster_test.bfbs",
schema="../reflection/reflection.fbs",
file="monster_test.bfbs",
include="include_test"
)
flatc_annotate(
schema="monster_test.fbs",
file="monsterdata_test.mon",
schema="monster_test.fbs",
file="monsterdata_test.mon",
include="include_test"
)
@@ -371,6 +385,12 @@ flatc(
)
flatc(
BASE_OPTS + PYTHON_OPTS,
schema="nested_union_test.fbs",
)
# Optional Scalars
optional_scalars_schema = "optional_scalars.fbs"
flatc(["--java", "--kotlin", "--lobster"], schema=optional_scalars_schema)
@@ -426,6 +446,7 @@ flatc(
)
flatc(SWIFT_OPTS, schema="optional_scalars.fbs", prefix=swift_prefix)
flatc(SWIFT_OPTS, schema="vector_has_test.fbs", prefix=swift_prefix)
flatc(SWIFT_OPTS, schema="nan_inf_test.fbs", prefix=swift_prefix)
flatc(
SWIFT_OPTS + ["--gen-object-api"],
schema="more_defaults.fbs",

View File

@@ -58,6 +58,11 @@ sed -i \
-e "s/\(__version__ = u\).*/\1\"$version\"/" \
python/flatbuffers/_version.py
echo "Updating python/setup.py..."
sed -i \
-e "s/\(version='\).*/\1$version',/" \
python/setup.py
echo "Updating FlatBuffers.podspec..."
sed -i \
-e "s/\(s.version\s*= \).*/\1'$version'/" \

View File

@@ -1,5 +1,6 @@
#include "annotated_binary_text_gen.h"
#include <algorithm>
#include <sstream>
#include <string>

View File

@@ -470,6 +470,13 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
std::string DefaultValue(const r::Field *field) const {
const r::BaseType base_type = field->type()->base_type();
if (IsFloatingPoint(base_type)) {
if (field->default_real() != field->default_real()) {
return "NaN";
} else if (field->default_real() == std::numeric_limits<double>::infinity()) {
return "Inf";
} else if (field->default_real() == -std::numeric_limits<double>::infinity()) {
return "-Inf";
}
return NumToString(field->default_real());
}
if (IsBool(base_type)) {

View File

@@ -1,5 +1,6 @@
#include "binary_annotator.h"
#include <algorithm>
#include <limits>
#include <string>
#include <vector>
@@ -1416,4 +1417,4 @@ bool BinaryAnnotator::ContainsSection(const uint64_t offset) {
it->second.regions.back().length;
}
} // namespace flatbuffers
} // namespace flatbuffers

View File

@@ -16,6 +16,8 @@
#include "flatbuffers/flatc.h"
#include <algorithm>
#include <limits>
#include <list>
#include <sstream>
@@ -88,7 +90,7 @@ const static FlatCOption options[] = {
"--no-prefix." },
{ "", "swift-implementation-only", "",
"Adds a @_implementationOnly to swift imports" },
{ "", "gen-inclues", "",
{ "", "gen-includes", "",
"(deprecated), this is the default behavior. If the original behavior is "
"required (no include statements) use --no-includes." },
{ "", "no-includes", "",
@@ -150,6 +152,8 @@ const static FlatCOption options[] = {
{ "", "go-import", "IMPORT",
"Generate the overriding import for flatbuffers in Golang (default is "
"\"github.com/google/flatbuffers/go\")." },
{ "", "go-module-name", "",
"Prefix local import paths of generated go code with the module name" },
{ "", "raw-binary", "",
"Allow binaries without file_identifier to be read. This may crash flatc "
"given a mismatched schema." },
@@ -215,14 +219,14 @@ const static FlatCOption options[] = {
"Allows (de)serialization of JSON text in the Object API. (requires "
"--gen-object-api)." },
{ "", "json-nested-bytes", "",
"Allow a nested_flatbuffer field to be parsed as a vector of bytes"
"Allow a nested_flatbuffer field to be parsed as a vector of bytes "
"in JSON, which is unsafe unless checked by a verifier afterwards." },
{ "", "ts-flat-files", "",
"Only generated one typescript file per .fbs file." },
{ "", "annotate", "SCHEMA",
"Annotate the provided BINARY_FILE with the specified SCHEMA file." },
{ "", "no-leak-private-annotation", "",
"Prevents multiple type of annotations within a Fbs SCHEMA file."
"Prevents multiple type of annotations within a Fbs SCHEMA file. "
"Currently this is required to generate private types in Rust" },
};
@@ -446,12 +450,17 @@ int FlatCompiler::Compile(int argc, const char **argv) {
} else if (arg == "--go-import") {
if (++argi >= argc) Error("missing golang import" + arg, true);
opts.go_import = argv[argi];
} else if (arg == "--go-module-name") {
if (++argi >= argc) Error("missing golang module name" + arg, true);
opts.go_module_name = argv[argi];
} else if (arg == "--defaults-json") {
opts.output_default_scalars_in_json = true;
} else if (arg == "--unknown-json") {
opts.skip_unexpected_fields_in_json = true;
} else if (arg == "--no-prefix") {
opts.prefixed_enums = false;
} else if (arg == "--cpp-minify-enums") {
opts.cpp_minify_enums = true;
} else if (arg == "--scoped-enums") {
opts.prefixed_enums = false;
opts.scoped_enums = true;

View File

@@ -16,6 +16,7 @@
// independent from idl_parser, since this code is not needed for most clients
#include <limits>
#include <string>
#include <unordered_set>
@@ -458,12 +459,10 @@ class CppGenerator : public BaseGenerator {
}
// Generate code for all the enum declarations.
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
const auto &enum_def = **it;
if (!enum_def.generated) {
SetNameSpace(enum_def.defined_namespace);
GenEnum(enum_def);
for (const auto enum_def : parser_.enums_.vec) {
if (!enum_def->generated) {
SetNameSpace(enum_def->defined_namespace);
GenEnum(*enum_def);
}
}
@@ -1230,17 +1229,21 @@ class CppGenerator : public BaseGenerator {
code_.SetValue("SEP", ",");
auto add_sep = false;
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
const auto &ev = **it;
for (const auto ev : enum_def.Vals()) {
if (add_sep) code_ += "{{SEP}}";
GenComment(ev.doc_comment, " ");
code_.SetValue("KEY", GenEnumValDecl(enum_def, Name(ev)));
GenComment(ev->doc_comment, " ");
code_.SetValue("KEY", GenEnumValDecl(enum_def, Name(*ev)));
code_.SetValue("VALUE",
NumToStringCpp(enum_def.ToString(ev),
NumToStringCpp(enum_def.ToString(*ev),
enum_def.underlying_type.base_type));
code_ += " {{KEY}} = {{VALUE}}\\";
add_sep = true;
}
if (opts_.cpp_minify_enums) {
code_ += "";
code_ += "};";
return;
}
const EnumVal *minv = enum_def.MinValue();
const EnumVal *maxv = enum_def.MaxValue();
@@ -1276,8 +1279,175 @@ class CppGenerator : public BaseGenerator {
"FLATBUFFERS_DEFINE_BITMASK_OPERATORS({{ENUM_NAME}}, {{BASE_TYPE}})";
}
code_ += "";
GenEnumArray(enum_def);
GenEnumStringTable(enum_def);
// Generate an array of all enumeration values
// Generate type traits for unions to map from a type to union enum value.
if (enum_def.is_union && !enum_def.uses_multiple_type_instances) {
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end();
++it) {
const auto &ev = **it;
if (it == enum_def.Vals().begin()) {
code_ += "template<typename T> struct {{ENUM_NAME}}Traits {";
} else {
auto name = GetUnionElement(ev, false, opts_);
code_ += "template<> struct {{ENUM_NAME}}Traits<" + name + "> {";
}
auto value = GetEnumValUse(enum_def, ev);
code_ += " static const {{ENUM_NAME}} enum_value = " + value + ";";
code_ += "};";
code_ += "";
}
}
GenEnumObjectBasedAPI(enum_def);
if (enum_def.is_union) {
code_ += UnionVerifySignature(enum_def) + ";";
code_ += UnionVectorVerifySignature(enum_def) + ";";
code_ += "";
}
}
// Generate a union type and a trait type for it.
void GenEnumObjectBasedAPI(const EnumDef &enum_def) {
if (!(opts_.generate_object_based_api && enum_def.is_union)) { return; }
code_.SetValue("NAME", Name(enum_def));
FLATBUFFERS_ASSERT(enum_def.Lookup("NONE"));
code_.SetValue("NONE", GetEnumValUse(enum_def, *enum_def.Lookup("NONE")));
if (!enum_def.uses_multiple_type_instances) {
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end();
++it) {
const auto &ev = **it;
if (it == enum_def.Vals().begin()) {
code_ += "template<typename T> struct {{NAME}}UnionTraits {";
} else {
auto name = GetUnionElement(ev, true, opts_);
code_ += "template<> struct {{NAME}}UnionTraits<" + name + "> {";
}
auto value = GetEnumValUse(enum_def, ev);
code_ += " static const {{ENUM_NAME}} enum_value = " + value + ";";
code_ += "};";
code_ += "";
}
}
code_ += "struct {{NAME}}Union {";
code_ += " {{NAME}} type;";
code_ += " void *value;";
code_ += "";
code_ += " {{NAME}}Union() : type({{NONE}}), value(nullptr) {}";
code_ += " {{NAME}}Union({{NAME}}Union&& u) FLATBUFFERS_NOEXCEPT :";
code_ += " type({{NONE}}), value(nullptr)";
code_ += " { std::swap(type, u.type); std::swap(value, u.value); }";
code_ += " {{NAME}}Union(const {{NAME}}Union &);";
code_ += " {{NAME}}Union &operator=(const {{NAME}}Union &u)";
code_ +=
" { {{NAME}}Union t(u); std::swap(type, t.type); std::swap(value, "
"t.value); return *this; }";
code_ +=
" {{NAME}}Union &operator=({{NAME}}Union &&u) FLATBUFFERS_NOEXCEPT";
code_ +=
" { std::swap(type, u.type); std::swap(value, u.value); return "
"*this; }";
code_ += " ~{{NAME}}Union() { Reset(); }";
code_ += "";
code_ += " void Reset();";
code_ += "";
if (!enum_def.uses_multiple_type_instances) {
code_ += " template <typename T>";
code_ += " void Set(T&& val) {";
code_ += " typedef typename std::remove_reference<T>::type RT;";
code_ += " Reset();";
code_ += " type = {{NAME}}UnionTraits<RT>::enum_value;";
code_ += " if (type != {{NONE}}) {";
code_ += " value = new RT(std::forward<T>(val));";
code_ += " }";
code_ += " }";
code_ += "";
}
code_ += " " + UnionUnPackSignature(enum_def, true) + ";";
code_ += " " + UnionPackSignature(enum_def, true) + ";";
code_ += "";
for (const auto ev : enum_def.Vals()) {
if (ev->IsZero()) { continue; }
const auto native_type = GetUnionElement(*ev, true, opts_);
code_.SetValue("NATIVE_TYPE", native_type);
code_.SetValue("NATIVE_NAME", Name(*ev));
code_.SetValue("NATIVE_ID", GetEnumValUse(enum_def, *ev));
code_ += " {{NATIVE_TYPE}} *As{{NATIVE_NAME}}() {";
code_ += " return type == {{NATIVE_ID}} ?";
code_ += " reinterpret_cast<{{NATIVE_TYPE}} *>(value) : nullptr;";
code_ += " }";
code_ += " const {{NATIVE_TYPE}} *As{{NATIVE_NAME}}() const {";
code_ += " return type == {{NATIVE_ID}} ?";
code_ +=
" reinterpret_cast<const {{NATIVE_TYPE}} *>(value) : nullptr;";
code_ += " }";
}
code_ += "};";
code_ += "";
GenEnumEquals(enum_def);
}
void GenEnumEquals(const EnumDef &enum_def) {
if (opts_.gen_compare) {
code_ += "";
code_ +=
"inline bool operator==(const {{NAME}}Union &lhs, const "
"{{NAME}}Union &rhs) {";
code_ += " if (lhs.type != rhs.type) return false;";
code_ += " switch (lhs.type) {";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end();
++it) {
const auto &ev = **it;
code_.SetValue("NATIVE_ID", GetEnumValUse(enum_def, ev));
if (ev.IsNonZero()) {
const auto native_type = GetUnionElement(ev, true, opts_);
code_.SetValue("NATIVE_TYPE", native_type);
code_ += " case {{NATIVE_ID}}: {";
code_ +=
" return *(reinterpret_cast<const {{NATIVE_TYPE}} "
"*>(lhs.value)) ==";
code_ +=
" *(reinterpret_cast<const {{NATIVE_TYPE}} "
"*>(rhs.value));";
code_ += " }";
} else {
code_ += " case {{NATIVE_ID}}: {";
code_ += " return true;"; // "NONE" enum value.
code_ += " }";
}
}
code_ += " default: {";
code_ += " return false;";
code_ += " }";
code_ += " }";
code_ += "}";
code_ += "";
code_ +=
"inline bool operator!=(const {{NAME}}Union &lhs, const "
"{{NAME}}Union &rhs) {";
code_ += " return !(lhs == rhs);";
code_ += "}";
code_ += "";
}
}
// Generate an array of all enumeration values
void GenEnumArray(const EnumDef &enum_def) {
auto num_fields = NumToString(enum_def.size());
code_ += "inline const {{ENUM_NAME}} (&EnumValues{{ENUM_NAME}}())[" +
num_fields + "] {";
@@ -1292,11 +1462,13 @@ class CppGenerator : public BaseGenerator {
code_ += " return values;";
code_ += "}";
code_ += "";
}
// Generate a generate string table for enum values.
// Problem is, if values are very sparse that could generate really big
// tables. Ideally in that case we generate a map lookup instead, but for
// the moment we simply don't output a table at all.
// Generate a string table for enum values.
// Problem is, if values are very sparse that could generate huge tables.
// Ideally in that case we generate a map lookup instead, but for the moment
// we simply don't output a table at all.
void GenEnumStringTable(const EnumDef &enum_def) {
auto range = enum_def.Distance();
// Average distance between values above which we consider a table
// "too sparse". Change at will.
@@ -1307,9 +1479,7 @@ class CppGenerator : public BaseGenerator {
NumToString(range + 1 + 1) + "] = {";
auto val = enum_def.Vals().front();
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end();
++it) {
auto ev = *it;
for (const auto &ev : enum_def.Vals()) {
for (auto k = enum_def.Distance(val, ev); k > 1; --k) {
code_ += " \"\",";
}
@@ -1342,180 +1512,16 @@ class CppGenerator : public BaseGenerator {
code_ += "";
} else {
code_ += "inline const char *EnumName{{ENUM_NAME}}({{ENUM_NAME}} e) {";
code_ += " switch (e) {";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end();
++it) {
const auto &ev = **it;
code_ += " case " + GetEnumValUse(enum_def, ev) + ": return \"" +
Name(ev) + "\";";
for (const auto &ev : enum_def.Vals()) {
code_ += " case " + GetEnumValUse(enum_def, *ev) + ": return \"" +
Name(*ev) + "\";";
}
code_ += " default: return \"\";";
code_ += " }";
code_ += "}";
code_ += "";
}
// Generate type traits for unions to map from a type to union enum value.
if (enum_def.is_union && !enum_def.uses_multiple_type_instances) {
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end();
++it) {
const auto &ev = **it;
if (it == enum_def.Vals().begin()) {
code_ += "template<typename T> struct {{ENUM_NAME}}Traits {";
} else {
auto name = GetUnionElement(ev, false, opts_);
code_ += "template<> struct {{ENUM_NAME}}Traits<" + name + "> {";
}
auto value = GetEnumValUse(enum_def, ev);
code_ += " static const {{ENUM_NAME}} enum_value = " + value + ";";
code_ += "};";
code_ += "";
}
}
if (opts_.generate_object_based_api && enum_def.is_union) {
// Generate a union type and a trait type for it.
code_.SetValue("NAME", Name(enum_def));
FLATBUFFERS_ASSERT(enum_def.Lookup("NONE"));
code_.SetValue("NONE", GetEnumValUse(enum_def, *enum_def.Lookup("NONE")));
if (!enum_def.uses_multiple_type_instances) {
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end();
++it) {
const auto &ev = **it;
if (it == enum_def.Vals().begin()) {
code_ += "template<typename T> struct {{NAME}}UnionTraits {";
} else {
auto name = GetUnionElement(ev, true, opts_);
code_ += "template<> struct {{NAME}}UnionTraits<" + name + "> {";
}
auto value = GetEnumValUse(enum_def, ev);
code_ += " static const {{ENUM_NAME}} enum_value = " + value + ";";
code_ += "};";
code_ += "";
}
}
code_ += "struct {{NAME}}Union {";
code_ += " {{NAME}} type;";
code_ += " void *value;";
code_ += "";
code_ += " {{NAME}}Union() : type({{NONE}}), value(nullptr) {}";
code_ += " {{NAME}}Union({{NAME}}Union&& u) FLATBUFFERS_NOEXCEPT :";
code_ += " type({{NONE}}), value(nullptr)";
code_ += " { std::swap(type, u.type); std::swap(value, u.value); }";
code_ += " {{NAME}}Union(const {{NAME}}Union &);";
code_ += " {{NAME}}Union &operator=(const {{NAME}}Union &u)";
code_ +=
" { {{NAME}}Union t(u); std::swap(type, t.type); std::swap(value, "
"t.value); return *this; }";
code_ +=
" {{NAME}}Union &operator=({{NAME}}Union &&u) FLATBUFFERS_NOEXCEPT";
code_ +=
" { std::swap(type, u.type); std::swap(value, u.value); return "
"*this; }";
code_ += " ~{{NAME}}Union() { Reset(); }";
code_ += "";
code_ += " void Reset();";
code_ += "";
if (!enum_def.uses_multiple_type_instances) {
code_ += " template <typename T>";
code_ += " void Set(T&& val) {";
code_ += " typedef typename std::remove_reference<T>::type RT;";
code_ += " Reset();";
code_ += " type = {{NAME}}UnionTraits<RT>::enum_value;";
code_ += " if (type != {{NONE}}) {";
code_ += " value = new RT(std::forward<T>(val));";
code_ += " }";
code_ += " }";
code_ += "";
}
code_ += " " + UnionUnPackSignature(enum_def, true) + ";";
code_ += " " + UnionPackSignature(enum_def, true) + ";";
code_ += "";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end();
++it) {
const auto &ev = **it;
if (ev.IsZero()) { continue; }
const auto native_type = GetUnionElement(ev, true, opts_);
code_.SetValue("NATIVE_TYPE", native_type);
code_.SetValue("NATIVE_NAME", Name(ev));
code_.SetValue("NATIVE_ID", GetEnumValUse(enum_def, ev));
code_ += " {{NATIVE_TYPE}} *As{{NATIVE_NAME}}() {";
code_ += " return type == {{NATIVE_ID}} ?";
code_ += " reinterpret_cast<{{NATIVE_TYPE}} *>(value) : nullptr;";
code_ += " }";
code_ += " const {{NATIVE_TYPE}} *As{{NATIVE_NAME}}() const {";
code_ += " return type == {{NATIVE_ID}} ?";
code_ +=
" reinterpret_cast<const {{NATIVE_TYPE}} *>(value) : nullptr;";
code_ += " }";
}
code_ += "};";
code_ += "";
if (opts_.gen_compare) {
code_ += "";
code_ +=
"inline bool operator==(const {{NAME}}Union &lhs, const "
"{{NAME}}Union &rhs) {";
code_ += " if (lhs.type != rhs.type) return false;";
code_ += " switch (lhs.type) {";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end();
++it) {
const auto &ev = **it;
code_.SetValue("NATIVE_ID", GetEnumValUse(enum_def, ev));
if (ev.IsNonZero()) {
const auto native_type = GetUnionElement(ev, true, opts_);
code_.SetValue("NATIVE_TYPE", native_type);
code_ += " case {{NATIVE_ID}}: {";
code_ +=
" return *(reinterpret_cast<const {{NATIVE_TYPE}} "
"*>(lhs.value)) ==";
code_ +=
" *(reinterpret_cast<const {{NATIVE_TYPE}} "
"*>(rhs.value));";
code_ += " }";
} else {
code_ += " case {{NATIVE_ID}}: {";
code_ += " return true;"; // "NONE" enum value.
code_ += " }";
}
}
code_ += " default: {";
code_ += " return false;";
code_ += " }";
code_ += " }";
code_ += "}";
code_ += "";
code_ +=
"inline bool operator!=(const {{NAME}}Union &lhs, const "
"{{NAME}}Union &rhs) {";
code_ += " return !(lhs == rhs);";
code_ += "}";
code_ += "";
}
}
if (enum_def.is_union) {
code_ += UnionVerifySignature(enum_def) + ";";
code_ += UnionVectorVerifySignature(enum_def) + ";";
code_ += "";
}
}
void GenUnionPost(const EnumDef &enum_def) {
@@ -2272,12 +2278,19 @@ class CppGenerator : public BaseGenerator {
// Generate CompareWithValue method for a key field.
void GenKeyFieldMethods(const FieldDef &field) {
FLATBUFFERS_ASSERT(field.key);
const bool is_string = (IsString(field.value.type));
const bool is_string = IsString(field.value.type);
const bool is_array = IsArray(field.value.type);
code_ += " bool KeyCompareLessThan(const {{STRUCT_NAME}} *o) const {";
code_ +=
" bool KeyCompareLessThan(const {{STRUCT_NAME}} * const o) const {";
if (is_string) {
// use operator< of flatbuffers::String
code_ += " return *{{FIELD_NAME}}() < *o->{{FIELD_NAME}}();";
} else if (is_array) {
const auto &elem_type = field.value.type.VectorType();
if (IsScalar(elem_type.base_type)) {
code_ += " return KeyCompareWithValue(o->{{FIELD_NAME}}()) < 0;";
}
} else {
code_ += " return {{FIELD_NAME}}() < o->{{FIELD_NAME}}();";
}
@@ -2286,7 +2299,27 @@ class CppGenerator : public BaseGenerator {
if (is_string) {
code_ += " int KeyCompareWithValue(const char *_{{FIELD_NAME}}) const {";
code_ += " return strcmp({{FIELD_NAME}}()->c_str(), _{{FIELD_NAME}});";
code_ += " }";
} else if (is_array) {
const auto &elem_type = field.value.type.VectorType();
if (IsScalar(elem_type.base_type)) {
std::string input_type = "flatbuffers::Array<" +
GenTypeBasic(elem_type, false) + ", " +
NumToString(elem_type.fixed_length) + ">";
code_.SetValue("INPUT_TYPE", input_type);
code_ +=
" int KeyCompareWithValue(const {{INPUT_TYPE}} *_{{FIELD_NAME}}"
") const { ";
code_ += " for (auto i = 0; i < {{FIELD_NAME}}()->size(); i++) {";
code_ += " const auto {{FIELD_NAME}}_l = {{FIELD_NAME}}_[i];";
code_ += " const auto {{FIELD_NAME}}_r = _{{FIELD_NAME}}->Get(i);";
code_ += " if({{FIELD_NAME}}_l != {{FIELD_NAME}}_r) ";
code_ +=
" return static_cast<int>({{FIELD_NAME}}_l > "
"{{FIELD_NAME}}_r)"
" - static_cast<int>({{FIELD_NAME}}_l < {{FIELD_NAME}}_r);";
code_ += " }";
code_ += " return 0;";
}
} else {
FLATBUFFERS_ASSERT(IsScalar(field.value.type.base_type));
auto type = GenTypeBasic(field.value.type, false);
@@ -2301,8 +2334,8 @@ class CppGenerator : public BaseGenerator {
code_ +=
" return static_cast<int>({{FIELD_NAME}}() > _{{FIELD_NAME}}) - "
"static_cast<int>({{FIELD_NAME}}() < _{{FIELD_NAME}});";
code_ += " }";
}
code_ += " }";
}
void GenTableUnionAsGetters(const FieldDef &field) {

View File

@@ -655,7 +655,7 @@ class CSharpGenerator : public BaseGenerator {
// Force compile time error if not using the same version runtime.
code += " public static void ValidateVersion() {";
code += " FlatBufferConstants.";
code += "FLATBUFFERS_22_10_25(); ";
code += "FLATBUFFERS_22_11_22(); ";
code += "}\n";
// Generate a special accessor for the table that when used as the root
@@ -1425,20 +1425,23 @@ class CSharpGenerator : public BaseGenerator {
code += "public ";
}
auto union_name = enum_def.name + "Union";
auto class_member = std::string("Value");
if (class_member == enum_def.name) { class_member += "_"; };
code += "class " + union_name + " {\n";
// Type
code += " public " + enum_def.name + " Type { get; set; }\n";
// Value
code += " public object Value { get; set; }\n";
code += " public object " + class_member + " { get; set; }\n";
code += "\n";
// Constructor
code += " public " + union_name + "() {\n";
code += " this.Type = " + enum_def.name + "." +
enum_def.Vals()[0]->name + ";\n";
code += " this.Value = null;\n";
code += " this." + class_member + " = null;\n";
code += " }\n\n";
// As<T>
code += " public T As<T>() where T : class { return this.Value as T; }\n";
code += " public T As<T>() where T : class { return this." + class_member +
" as T; }\n";
// As, From
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
auto &ev = **it;
@@ -1459,7 +1462,8 @@ class CSharpGenerator : public BaseGenerator {
code += " " + accessibility + " static " + union_name + " From" +
ev.name + "(" + type_name + " _" + lower_ev_name +
") { return new " + union_name + "{ Type = " + Name(enum_def) +
"." + Name(ev) + ", Value = _" + lower_ev_name + " }; }\n";
"." + Name(ev) + ", " + class_member + " = _" + lower_ev_name +
" }; }\n";
}
code += "\n";
// Pack()
@@ -1581,6 +1585,8 @@ class CSharpGenerator : public BaseGenerator {
bool is_vector) const {
auto &code = *code_ptr;
std::string varialbe_name = "_o." + camel_name;
std::string class_member = "Value";
if (class_member == camel_name) class_member += "_";
std::string type_suffix = "";
std::string func_suffix = "()";
std::string indent = " ";
@@ -1608,7 +1614,8 @@ class CSharpGenerator : public BaseGenerator {
} else {
code += indent + " case " + NamespacedName(enum_def) + "." + ev.name +
":\n";
code += indent + " " + varialbe_name + ".Value = this." + camel_name;
code += indent + " " + varialbe_name + "." + class_member +
" = this." + camel_name;
if (IsString(ev.union_type)) {
code += "AsString" + func_suffix + ";\n";
} else {

View File

@@ -16,6 +16,7 @@
// independent from idl_parser, since this code is not needed for most clients
#include <cassert>
#include <cmath>
#include "flatbuffers/code_generators.h"
#include "flatbuffers/flatbuffers.h"
@@ -69,7 +70,7 @@ static std::set<std::string> DartKeywords() {
"dynamic", "implements", "set",
};
}
} // namespace
} // namespace
const std::string _kFb = "fb";
@@ -84,6 +85,27 @@ class DartGenerator : public BaseGenerator {
: BaseGenerator(parser, path, file_name, "", ".", "dart"),
namer_(WithFlagOptions(DartDefaultConfig(), parser.opts, path),
DartKeywords()) {}
template<typename T>
void import_generator(const std::vector<T *> &definitions,
const std::string &included,
std::set<std::string> &imports) {
for (const auto &item : definitions) {
if (item->file == included) {
std::string component = namer_.Namespace(*item->defined_namespace);
std::string filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(item->file));
std::string filename =
namer_.File(filebase + (component.empty() ? "" : "_" + component));
imports.emplace("import './" + filename + "'" +
(component.empty()
? ";\n"
: " as " + ImportAliasName(component) + ";\n"));
}
}
}
// Iterate through all definitions we haven't generate code for (enums,
// structs, and tables) and output them to a single file.
bool generate() {
@@ -92,6 +114,20 @@ class DartGenerator : public BaseGenerator {
GenerateEnums(namespace_code);
GenerateStructs(namespace_code);
std::set<std::string> imports;
for (const auto &included_file : parser_.GetIncludedFiles()) {
if (included_file.filename == parser_.file_being_parsed_) continue;
import_generator(parser_.structs_.vec, included_file.filename, imports);
import_generator(parser_.enums_.vec, included_file.filename, imports);
}
std::string import_code = "";
for (const auto &file : imports) { import_code += file; }
import_code += import_code.empty() ? "" : "\n";
for (auto kv = namespace_code.begin(); kv != namespace_code.end(); ++kv) {
code.clear();
code = code + "// " + FlatBuffersGeneratedWarning() + "\n";
@@ -112,7 +148,10 @@ class DartGenerator : public BaseGenerator {
"' as " + ImportAliasName(kv2->first) + ";\n";
}
}
code += "\n";
code += import_code;
code += kv->second;
if (!SaveFile(Filename(kv->first).c_str(), code, false)) { return false; }
@@ -721,16 +760,17 @@ class DartGenerator : public BaseGenerator {
if (!value.constant.empty() && value.constant != "0") {
if (IsBool(value.type.base_type)) {
return "true";
} else if (value.constant == "nan" || value.constant == "+nan" ||
value.constant == "-nan") {
return "double.nan";
} else if (value.constant == "inf" || value.constant == "+inf") {
return "double.infinity";
} else if (value.constant == "-inf") {
return "double.negativeInfinity";
} else {
return value.constant;
}
if (IsScalar(value.type.base_type)) {
if (StringIsFlatbufferNan(value.constant)) {
return "double.nan";
} else if (StringIsFlatbufferPositiveInfinity(value.constant)) {
return "double.infinity";
} else if (StringIsFlatbufferNegativeInfinity(value.constant)) {
return "double.negativeInfinity";
}
}
return value.constant;
} else if (IsBool(value.type.base_type)) {
return "false";
} else if (IsScalar(value.type.base_type) && !IsUnion(value.type)) {

View File

@@ -137,6 +137,7 @@ std::string GenerateFBS(const Parser &parser, const std::string &file_name) {
schema += " " + field.name + ":" + GenType(field.value.type);
if (field.value.constant != "0") schema += " = " + field.value.constant;
if (field.IsRequired()) schema += " (required)";
if (field.key) schema += " (key)";
schema += ";\n";
}
}

View File

@@ -16,9 +16,12 @@
// independent from idl_parser, since this code is not needed for most clients
#include <algorithm>
#include <cmath>
#include <sstream>
#include <string>
#include "flatbuffers/base.h"
#include "flatbuffers/code_generators.h"
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
@@ -77,7 +80,7 @@ static Namer::Config GoDefaultConfig() {
/*filename_extension=*/".go" };
}
} // namespace
} // namespace
class GoGenerator : public BaseGenerator {
public:
@@ -101,6 +104,8 @@ class GoGenerator : public BaseGenerator {
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
tracked_imported_namespaces_.clear();
needs_math_import_ = false;
needs_bytes_import_ = false;
needs_imports = false;
std::string enumcode;
GenEnum(**it, &enumcode);
@@ -120,6 +125,8 @@ class GoGenerator : public BaseGenerator {
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
tracked_imported_namespaces_.clear();
needs_math_import_ = false;
needs_bytes_import_ = false;
std::string declcode;
GenStruct(**it, &declcode);
if (parser_.opts.one_file) {
@@ -148,11 +155,13 @@ class GoGenerator : public BaseGenerator {
const IdlNamer namer_;
struct NamespacePtrLess {
bool operator()(const Namespace *a, const Namespace *b) const {
return *a < *b;
bool operator()(const Definition *a, const Definition *b) const {
return *a->defined_namespace < *b->defined_namespace;
}
};
std::set<const Namespace *, NamespacePtrLess> tracked_imported_namespaces_;
std::set<const Definition *, NamespacePtrLess> tracked_imported_namespaces_;
bool needs_math_import_ = false;
bool needs_bytes_import_ = false;
// Most field accessors need to retrieve and test the field offset first,
// this is the prefix code for that.
@@ -175,8 +184,7 @@ class GoGenerator : public BaseGenerator {
// Construct the name of the type for this enum.
std::string GetEnumTypeName(const EnumDef &enum_def) {
return WrapInNameSpaceAndTrack(enum_def.defined_namespace,
namer_.Type(enum_def));
return WrapInNameSpaceAndTrack(&enum_def, namer_.Type(enum_def));
}
// Create a type for the enum values.
@@ -485,6 +493,34 @@ class GoGenerator : public BaseGenerator {
code += "}\n\n";
}
void GetMemberOfVectorOfStructByKey(const StructDef &struct_def,
const FieldDef &field,
std::string *code_ptr) {
std::string &code = *code_ptr;
auto vectortype = field.value.type.VectorType();
FLATBUFFERS_ASSERT(vectortype.struct_def->has_key);
auto &vector_struct_fields = vectortype.struct_def->fields.vec;
auto kit =
std::find_if(vector_struct_fields.begin(), vector_struct_fields.end(),
[&](FieldDef *field) { return field->key; });
auto &key_field = **kit;
FLATBUFFERS_ASSERT(key_field.key);
GenReceiver(struct_def, code_ptr);
code += " " + namer_.Field(field) + "ByKey";
code += "(obj *" + TypeName(field);
code += ", key " + NativeType(key_field.value.type) + ") bool" +
OffsetPrefix(field);
code += "\t\tx := rcv._tab.Vector(o)\n";
code += "\t\treturn ";
code += "obj.LookupByKey(key, x, rcv._tab.Bytes)\n";
code += "\t}\n";
code += "\treturn false\n";
code += "}\n\n";
}
// Get the value of a vector's non-struct member.
void GetMemberOfVectorOfNonStruct(const StructDef &struct_def,
const FieldDef &field,
@@ -686,6 +722,12 @@ class GoGenerator : public BaseGenerator {
auto vectortype = field.value.type.VectorType();
if (vectortype.base_type == BASE_TYPE_STRUCT) {
GetMemberOfVectorOfStruct(struct_def, field, code_ptr);
// TODO(michaeltle): Support querying fixed struct by key.
// Currently, we only support keyed tables.
if (!vectortype.struct_def->fixed &&
vectortype.struct_def->has_key) {
GetMemberOfVectorOfStructByKey(struct_def, field, code_ptr);
}
} else {
GetMemberOfVectorOfNonStruct(struct_def, field, code_ptr);
}
@@ -820,6 +862,12 @@ class GoGenerator : public BaseGenerator {
GenStructAccessor(struct_def, field, code_ptr);
GenStructMutator(struct_def, field, code_ptr);
// TODO(michaeltle): Support querying fixed struct by key. Currently,
// we only support keyed tables.
if (!struct_def.fixed && field.key) {
GenKeyCompare(struct_def, field, code_ptr);
GenLookupByKey(struct_def, field, code_ptr);
}
}
// Generate builders
@@ -832,6 +880,79 @@ class GoGenerator : public BaseGenerator {
}
}
void GenKeyCompare(const StructDef &struct_def, const FieldDef &field,
std::string *code_ptr) {
FLATBUFFERS_ASSERT(struct_def.has_key);
FLATBUFFERS_ASSERT(field.key);
std::string &code = *code_ptr;
code += "func " + namer_.Type(struct_def) + "KeyCompare(";
code += "o1, o2 flatbuffers.UOffsetT, buf []byte) bool {\n";
code += "\tobj1 := &" + namer_.Type(struct_def) + "{}\n";
code += "\tobj2 := &" + namer_.Type(struct_def) + "{}\n";
code += "\tobj1.Init(buf, flatbuffers.UOffsetT(len(buf)) - o1)\n";
code += "\tobj2.Init(buf, flatbuffers.UOffsetT(len(buf)) - o2)\n";
if (IsString(field.value.type)) {
code += "\treturn string(obj1." + namer_.Function(field.name) + "()) < ";
code += "string(obj2." + namer_.Function(field.name) + "())\n";
} else {
code += "\treturn obj1." + namer_.Function(field.name) + "() < ";
code += "obj2." + namer_.Function(field.name) + "()\n";
}
code += "}\n\n";
}
void GenLookupByKey(const StructDef &struct_def, const FieldDef &field,
std::string *code_ptr) {
FLATBUFFERS_ASSERT(struct_def.has_key);
FLATBUFFERS_ASSERT(field.key);
std::string &code = *code_ptr;
GenReceiver(struct_def, code_ptr);
code += " LookupByKey(";
code += "key " + NativeType(field.value.type) + ", ";
code += "vectorLocation flatbuffers.UOffsetT, ";
code += "buf []byte) bool {\n";
code += "\tspan := flatbuffers.GetUOffsetT(buf[vectorLocation - 4:])\n";
code += "\tstart := flatbuffers.UOffsetT(0)\n";
code += "\tfor span != 0 {\n";
code += "\t\tmiddle := span / 2\n";
code += "\t\ttableOffset := flatbuffers.GetIndirectOffset(buf, ";
code += "vectorLocation+ 4 * (start + middle))\n";
code += "\t\tobj := &" + namer_.Type(struct_def) + "{}\n";
code += "\t\tobj.Init(buf, tableOffset)\n";
if (IsString(field.value.type)) {
code += "\t\tbKey := []byte(key)\n";
needs_bytes_import_ = true;
code +=
"\t\tcomp := bytes.Compare(obj." + namer_.Function(field.name) + "()";
code += ", bKey)\n";
} else {
code += "\t\tval := obj." + namer_.Function(field.name) + "()\n";
code += "\t\tcomp := 0\n";
code += "\t\tif val > key {\n";
code += "\t\t\tcomp = 1\n";
code += "\t\t} else if val < key {\n";
code += "\t\t\tcomp = -1\n";
code += "\t\t}\n";
}
code += "\t\tif comp > 0 {\n";
code += "\t\t\tspan = middle\n";
code += "\t\t} else if comp < 0 {\n";
code += "\t\t\tmiddle += 1\n";
code += "\t\t\tstart += middle\n";
code += "\t\t\tspan -= middle\n";
code += "\t\t} else {\n";
code += "\t\t\trcv.Init(buf, tableOffset)\n";
code += "\t\t\treturn true\n";
code += "\t\t}\n";
code += "\t}\n";
code += "\treturn false\n";
code += "}\n\n";
}
void GenNativeStruct(const StructDef &struct_def, std::string *code_ptr) {
std::string &code = *code_ptr;
@@ -901,11 +1022,14 @@ class GoGenerator : public BaseGenerator {
const EnumVal &ev = **it2;
if (ev.IsZero()) continue;
code += "\tcase " + namer_.EnumVariant(enum_def, ev) + ":\n";
code += "\t\tx := " + ev.union_type.struct_def->name + "{_tab: table}\n";
code += "\t\tvar x " +
WrapInNameSpaceAndTrack(ev.union_type.struct_def,
ev.union_type.struct_def->name) +
"\n";
code += "\t\tx.Init(table.Bytes, table.Pos)\n";
code += "\t\treturn &" +
WrapInNameSpaceAndTrack(enum_def.defined_namespace,
NativeName(enum_def)) +
WrapInNameSpaceAndTrack(&enum_def, NativeName(enum_def)) +
"{ Type: " + namer_.EnumVariant(enum_def, ev) +
", Value: x.UnPack() }\n";
}
@@ -1066,7 +1190,8 @@ class GoGenerator : public BaseGenerator {
code += "\tfor j := 0; j < " + length + "; j++ {\n";
if (field.value.type.element == BASE_TYPE_STRUCT) {
code += "\t\tx := " +
WrapInNameSpaceAndTrack(*field.value.type.struct_def) +
WrapInNameSpaceAndTrack(field.value.type.struct_def,
field.value.type.struct_def->name) +
"{}\n";
code += "\t\trcv." + field_field + "(&x, j)\n";
}
@@ -1233,7 +1358,8 @@ class GoGenerator : public BaseGenerator {
switch (type.base_type) {
case BASE_TYPE_STRING: return "[]byte";
case BASE_TYPE_VECTOR: return GenTypeGet(type.VectorType());
case BASE_TYPE_STRUCT: return WrapInNameSpaceAndTrack(*type.struct_def);
case BASE_TYPE_STRUCT:
return WrapInNameSpaceAndTrack(type.struct_def, type.struct_def->name);
case BASE_TYPE_UNION:
// fall through
default: return "*flatbuffers.Table";
@@ -1276,6 +1402,23 @@ class GoGenerator : public BaseGenerator {
switch (field.value.type.base_type) {
case BASE_TYPE_BOOL:
return field.value.constant == "0" ? "false" : "true";
case BASE_TYPE_FLOAT:
case BASE_TYPE_DOUBLE: {
const std::string float_type =
field.value.type.base_type == BASE_TYPE_FLOAT ? "float32"
: "float64";
if (StringIsFlatbufferNan(field.value.constant)) {
needs_math_import_ = true;
return float_type + "(math.NaN())";
} else if (StringIsFlatbufferPositiveInfinity(field.value.constant)) {
needs_math_import_ = true;
return float_type + "(math.Inf(1))";
} else if (StringIsFlatbufferNegativeInfinity(field.value.constant)) {
needs_math_import_ = true;
return float_type + "(math.Inf(-1))";
}
return field.value.constant;
}
default: return field.value.constant;
}
}
@@ -1300,11 +1443,11 @@ class GoGenerator : public BaseGenerator {
} else if (IsVector(type)) {
return "[]" + NativeType(type.VectorType());
} else if (type.base_type == BASE_TYPE_STRUCT) {
return "*" + WrapInNameSpaceAndTrack(type.struct_def->defined_namespace,
return "*" + WrapInNameSpaceAndTrack(type.struct_def,
NativeName(*type.struct_def));
} else if (type.base_type == BASE_TYPE_UNION) {
return "*" + WrapInNameSpaceAndTrack(type.enum_def->defined_namespace,
NativeName(*type.enum_def));
return "*" +
WrapInNameSpaceAndTrack(type.enum_def, NativeName(*type.enum_def));
}
FLATBUFFERS_ASSERT(0);
return std::string();
@@ -1328,7 +1471,10 @@ class GoGenerator : public BaseGenerator {
code += "package " + name_space_name + "\n\n";
if (needs_imports) {
code += "import (\n";
if (is_enum) { code += "\t\"strconv\"\n\n"; }
if (needs_bytes_import_) code += "\t\"bytes\"\n";
// math is needed to support non-finite scalar default values.
if (needs_math_import_) { code += "\t\"math\"\n"; }
if (is_enum) { code += "\t\"strconv\"\n"; }
if (!parser_.opts.go_import.empty()) {
code += "\tflatbuffers \"" + parser_.opts.go_import + "\"\n";
} else {
@@ -1338,13 +1484,22 @@ class GoGenerator : public BaseGenerator {
code += "\n";
for (auto it = tracked_imported_namespaces_.begin();
it != tracked_imported_namespaces_.end(); ++it) {
code += "\t" + NamespaceImportName(*it) + " \"" +
NamespaceImportPath(*it) + "\"\n";
if ((*it)->defined_namespace->components.empty()) {
code += "\t" + (*it)->name + " \"" + (*it)->name + "\"\n";
} else {
code += "\t" + NamespaceImportName((*it)->defined_namespace) +
" \"" + NamespaceImportPath((*it)->defined_namespace) +
"\"\n";
}
}
}
code += ")\n\n";
} else {
if (is_enum) { code += "import \"strconv\"\n\n"; }
if (needs_math_import_) {
// math is needed to support non-finite scalar default values.
code += "import \"math\"\n\n";
}
}
}
@@ -1356,7 +1511,8 @@ class GoGenerator : public BaseGenerator {
Namespace &ns = go_namespace_.components.empty() ? *def.defined_namespace
: go_namespace_;
std::string code = "";
BeginFile(LastNamespacePart(ns), needs_imports, is_enum, &code);
BeginFile(ns.components.empty() ? def.name : LastNamespacePart(ns),
needs_imports, is_enum, &code);
code += classcode;
// Strip extra newlines at end of file to make it gofmt-clean.
while (code.length() > 2 && code.substr(code.length() - 2) == "\n\n") {
@@ -1376,21 +1532,24 @@ class GoGenerator : public BaseGenerator {
// Create the full path for the imported namespace (format: A/B/C).
std::string NamespaceImportPath(const Namespace *ns) const {
return namer_.Directories(*ns, SkipDir::OutputPathAndTrailingPathSeparator);
std::string path =
namer_.Directories(*ns, SkipDir::OutputPathAndTrailingPathSeparator);
if (!parser_.opts.go_module_name.empty()) {
path = parser_.opts.go_module_name + "/" + path;
}
return path;
}
// Ensure that a type is prefixed with its go package import name if it is
// used outside of its namespace.
std::string WrapInNameSpaceAndTrack(const Namespace *ns,
std::string WrapInNameSpaceAndTrack(const Definition *def,
const std::string &name) {
if (CurrentNameSpace() == ns) return name;
tracked_imported_namespaces_.insert(ns);
return NamespaceImportName(ns) + "." + name;
}
std::string WrapInNameSpaceAndTrack(const Definition &def) {
return WrapInNameSpaceAndTrack(def.defined_namespace, def.name);
if (CurrentNameSpace() == def->defined_namespace) return name;
tracked_imported_namespaces_.insert(def);
if (def->defined_namespace->components.empty())
return def->name + "." + name;
else
return NamespaceImportName(def->defined_namespace) + "." + name;
}
const Namespace *CurrentNameSpace() const { return cur_name_space_; }

View File

@@ -669,7 +669,7 @@ class JavaGenerator : public BaseGenerator {
// Force compile time error if not using the same version runtime.
code += " public static void ValidateVersion() {";
code += " Constants.";
code += "FLATBUFFERS_22_10_25(); ";
code += "FLATBUFFERS_22_11_22(); ";
code += "}\n";
// Generate a special accessor for the table that when used as the root

View File

@@ -14,7 +14,9 @@
* limitations under the License.
*/
#include <algorithm>
#include <iostream>
#include <limits>
#include "flatbuffers/code_generators.h"
#include "flatbuffers/idl.h"

View File

@@ -505,7 +505,7 @@ class KotlinGenerator : public BaseGenerator {
// runtime.
GenerateFunOneLine(
writer, "validateVersion", "", "",
[&]() { writer += "Constants.FLATBUFFERS_22_10_25()"; },
[&]() { writer += "Constants.FLATBUFFERS_22_11_22()"; },
options.gen_jvmstatic);
GenerateGetRootAsAccessors(namer_.Type(struct_def), writer, options);

View File

@@ -1108,13 +1108,25 @@ class PythonGenerator : public BaseGenerator {
code += GenIndents(1) + "@classmethod";
code += GenIndents(1) + "def InitFromBuf(cls, buf, pos):";
code += GenIndents(2) + "n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, 0)";
code += GenIndents(2) + struct_var + " = " + struct_type + "()";
code += GenIndents(2) + struct_var + ".Init(buf, pos+n)";
code += GenIndents(2) + struct_var + ".Init(buf, pos)";
code += GenIndents(2) + "return cls.InitFromObj(" + struct_var + ")";
code += "\n";
}
void InitializeFromPackedBuf(const StructDef &struct_def,
std::string *code_ptr) const {
auto &code = *code_ptr;
const auto struct_var = namer_.Variable(struct_def);
const auto struct_type = namer_.Type(struct_def);
code += GenIndents(1) + "@classmethod";
code += GenIndents(1) + "def InitFromPackedBuf(cls, buf, pos=0):";
code += GenIndents(2) + "n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos)";
code += GenIndents(2) + "return cls.InitFromBuf(buf, pos+n)";
code += "\n";
}
void InitializeFromObjForObject(const StructDef &struct_def,
std::string *code_ptr) const {
auto &code = *code_ptr;
@@ -1129,6 +1141,23 @@ class PythonGenerator : public BaseGenerator {
code += "\n";
}
void GenCompareOperator(const StructDef &struct_def,
std::string *code_ptr) const {
auto &code = *code_ptr;
code += GenIndents(1) + "def __eq__(self, other):";
code += GenIndents(2) + "return type(self) == type(other)";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
if (field.deprecated) continue;
// Wrties the comparison statement for this field.
const auto field_field = namer_.Field(field);
code += " and \\" + GenIndents(3) + "self." + field_field + " == " + "other." + field_field;
}
code += "\n";
}
void GenUnPackForStruct(const StructDef &struct_def, const FieldDef &field,
std::string *code_ptr) const {
auto &code = *code_ptr;
@@ -1148,8 +1177,8 @@ class PythonGenerator : public BaseGenerator {
code += field_type + "()";
}
code += ") is not None:";
code += GenIndents(3) + "self." + field_field + " = " + field_type +
"T.InitFromObj(" + struct_var + "." + field_method + "(";
code += GenIndents(3) + "self." + field_field + " = " + namer_.ObjectType(field_type) +
+ ".InitFromObj(" + struct_var + "." + field_method + "(";
// A struct's accessor requires a struct buf instance.
if (struct_def.fixed && field.value.type.base_type == BASE_TYPE_STRUCT) {
code += field_type + "()";
@@ -1199,8 +1228,8 @@ class PythonGenerator : public BaseGenerator {
"(i) is None:";
code += GenIndents(5) + "self." + field_field + ".append(None)";
code += GenIndents(4) + "else:";
code += GenIndents(5) + one_instance + " = " + field_type +
"T.InitFromObj(" + struct_var + "." + field_method + "(i))";
code += GenIndents(5) + one_instance + " = " + namer_.ObjectType(field_type) +
".InitFromObj(" + struct_var + "." + field_method + "(i))";
code +=
GenIndents(5) + "self." + field_field + ".append(" + one_instance + ")";
}
@@ -1230,8 +1259,8 @@ class PythonGenerator : public BaseGenerator {
"(i) is None:";
code += GenIndents(5) + "self." + field_field + ".append(None)";
code += GenIndents(4) + "else:";
code += GenIndents(5) + one_instance + " = " + field_type +
"T.InitFromObj(" + struct_var + "." + field_method + "(i))";
code += GenIndents(5) + one_instance + " = " + namer_.ObjectType(field_type) +
".InitFromObj(" + struct_var + "." + field_method + "(i))";
code +=
GenIndents(5) + "self." + field_field + ".append(" + one_instance + ")";
}
@@ -1607,8 +1636,14 @@ class PythonGenerator : public BaseGenerator {
InitializeFromBuf(struct_def, &code);
InitializeFromPackedBuf(struct_def, &code);
InitializeFromObjForObject(struct_def, &code);
if (parser_.opts.gen_compare) {
GenCompareOperator(struct_def, &code);
}
GenUnPack(struct_def, &code);
if (struct_def.fixed) {

View File

@@ -16,6 +16,8 @@
// independent from idl_parser, since this code is not needed for most clients
#include <cmath>
#include "flatbuffers/code_generators.h"
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
@@ -1046,8 +1048,19 @@ class RustGenerator : public BaseGenerator {
if (field.IsOptional() && !IsUnion(field.value.type)) { return "None"; }
}
switch (GetFullType(field.value.type)) {
case ftInteger:
case ftInteger: {
return field.value.constant;
}
case ftFloat: {
const std::string float_prefix =
(field.value.type.base_type == BASE_TYPE_FLOAT) ? "f32::" : "f64::";
if (StringIsFlatbufferNan(field.value.constant)) {
return float_prefix + "NAN";
} else if (StringIsFlatbufferPositiveInfinity(field.value.constant)) {
return float_prefix + "INFINITY";
} else if (StringIsFlatbufferNegativeInfinity(field.value.constant)) {
return float_prefix + "NEG_INFINITY";
}
return field.value.constant;
}
case ftBool: {

View File

@@ -258,11 +258,9 @@ class SwiftGenerator : public BaseGenerator {
IsEnum(field.value.type) ? "{{BASEVALUE}}" : "{{VALUETYPE}}";
code_ += "private var _{{FIELDVAR}}: " + valueType;
const auto accessing_value = IsEnum(field.value.type) ? ".value" : "";
const auto is_bool = IsBool(field.value.type.base_type);
const auto base_value =
IsStruct(field.value.type) ? (type + "()")
: is_bool ? ("0" == field.value.constant ? "false" : "true")
: field.value.constant;
: SwiftConstant(field);
main_constructor.push_back("_" + field_var + " = " + field_var +
accessing_value);
@@ -378,35 +376,6 @@ class SwiftGenerator : public BaseGenerator {
code_ += "}\n";
}
// Generates the create function for swift
void GenStructWriter(const StructDef &struct_def) {
const bool is_private_access =
parser_.opts.swift_implementation_only ||
struct_def.attributes.Lookup("private") != nullptr;
code_.SetValue("ACCESS_TYPE", is_private_access ? "internal" : "public");
code_.SetValue("STRUCTNAME", namer_.NamespacedType(struct_def));
code_.SetValue("SHORT_STRUCTNAME", namer_.Method(struct_def));
code_ += "extension {{STRUCTNAME}} {";
Indent();
code_ += "@discardableResult";
code_ +=
"{{ACCESS_TYPE}} static func create{{SHORT_STRUCTNAME}}(builder: inout "
"FlatBufferBuilder, \\";
std::string func_header = "";
GenerateStructArgs(struct_def, &func_header, "", "");
code_ += func_header.substr(0, func_header.size() - 2) + "\\";
code_ += ") -> Offset {";
Indent();
code_ +=
"builder.createStructOf(size: {{STRUCTNAME}}.size, alignment: "
"{{STRUCTNAME}}.alignment)";
code_ += "return builder.endStruct()";
Outdent();
code_ += "}\n";
Outdent();
code_ += "}\n";
}
void GenerateStructArgs(const StructDef &struct_def, std::string *code_ptr,
const std::string &nameprefix,
const std::string &object_name,
@@ -430,11 +399,7 @@ class SwiftGenerator : public BaseGenerator {
code += nameprefix + field_var + ": " + type;
if (!IsEnum(field.value.type)) {
code += " = ";
const auto is_bool = IsBool(field.value.type.base_type);
const auto constant =
is_bool ? ("0" == field.value.constant ? "false" : "true")
: field.value.constant;
code += constant;
code += SwiftConstant(field);
}
code += ", ";
continue;
@@ -633,7 +598,7 @@ class SwiftGenerator : public BaseGenerator {
code_.SetValue("FIELDVAR", namer_.Variable(field));
code_.SetValue("VALUETYPE", nullable_type);
code_.SetValue("OFFSET", namer_.Field(field));
code_.SetValue("CONSTANT", field.value.constant);
code_.SetValue("CONSTANT", SwiftConstant(field));
std::string check_if_vector =
(IsVector(field.value.type) || IsArray(field.value.type)) ? "VectorOf("
: "(";
@@ -659,7 +624,7 @@ class SwiftGenerator : public BaseGenerator {
const auto default_value =
IsEnum(field.value.type)
? (field.IsOptional() ? "nil" : GenEnumDefaultValue(field))
: field.value.constant;
: SwiftConstant(field);
create_func_header.push_back(
"" + field_field + ": " + nullable_type + " = " +
(field.IsOptional() ? "nil" : default_value));
@@ -667,8 +632,7 @@ class SwiftGenerator : public BaseGenerator {
}
if (IsBool(field.value.type.base_type)) {
std::string default_value =
"0" == field.value.constant ? "false" : "true";
std::string default_value = SwiftConstant(field);
code_.SetValue("CONSTANT", default_value);
code_.SetValue("VALUETYPE", field.IsOptional() ? "Bool?" : "Bool");
@@ -743,7 +707,7 @@ class SwiftGenerator : public BaseGenerator {
code_.SetValue("FIELDMETHOD", namer_.Method(field));
code_.SetValue("VALUETYPE", type);
code_.SetValue("OFFSET", namer_.Constant(field.name));
code_.SetValue("CONSTANT", field.value.constant);
code_.SetValue("CONSTANT", SwiftConstant(field));
bool opt_scalar =
field.IsOptional() && IsScalar(field.value.type.base_type);
std::string def_Val = opt_scalar ? "nil" : "{{CONSTANT}}";
@@ -761,7 +725,7 @@ class SwiftGenerator : public BaseGenerator {
if (IsBool(field.value.type.base_type)) {
std::string default_value =
field.IsOptional() ? "nil"
: ("0" == field.value.constant ? "false" : "true");
: SwiftConstant(field);
code_.SetValue("CONSTANT", default_value);
code_.SetValue("VALUETYPE", "Bool");
code_ += GenReaderMainBody(optional) + "\\";
@@ -809,7 +773,7 @@ class SwiftGenerator : public BaseGenerator {
break;
case BASE_TYPE_STRING: {
const auto default_string = "\"" + field.value.constant + "\"";
const auto default_string = "\"" + SwiftConstant(field) + "\"";
code_.SetValue("VALUETYPE", GenType(field.value.type));
code_.SetValue("CONSTANT", field.IsDefault() ? default_string : "nil");
code_ += GenReaderMainBody(is_required) + GenOffset() +
@@ -1017,20 +981,20 @@ class SwiftGenerator : public BaseGenerator {
field.value.type.VectorType().base_type != BASE_TYPE_UTYPE;
code_.SetValue("FIELDVAR", namer_.Variable(field));
code_.SetValue("CONSTANT", field.value.constant);
code_.SetValue("CONSTANT", SwiftConstant(field));
bool should_indent = true;
if (is_non_union_vector) {
code_ += "if {{FIELDVAR}}Count > 0 {";
} else if (IsEnum(type) && !field.IsOptional()) {
code_.SetValue("CONSTANT", GenEnumDefaultValue(field));
code_ += "if {{FIELDVAR}} != {{CONSTANT}} {";
} else if (IsFloat(type.base_type) && StringIsFlatbufferNan(field.value.constant)) {
code_ += "if !{{FIELDVAR}}.isNaN {";
} else if (IsScalar(type.base_type) && !IsEnum(type) &&
!IsBool(type.base_type) && !field.IsOptional()) {
code_ += "if {{FIELDVAR}} != {{CONSTANT}} {";
} else if (IsBool(type.base_type) && !field.IsOptional()) {
std::string default_value =
"0" == field.value.constant ? "false" : "true";
code_.SetValue("CONSTANT", default_value);
code_.SetValue("CONSTANT", SwiftConstant(field));
code_ += "if {{FIELDVAR}} != {{CONSTANT}} {";
} else {
should_indent = false;
@@ -1578,13 +1542,13 @@ class SwiftGenerator : public BaseGenerator {
if (field.IsRequired()) {
std::string default_value =
field.IsDefault() ? field.value.constant : "";
field.IsDefault() ? SwiftConstant(field) : "";
base_constructor.push_back(field_var + " = \"" + default_value +
"\"");
break;
}
if (field.IsDefault() && !field.IsRequired()) {
std::string value = field.IsDefault() ? field.value.constant : "nil";
std::string value = field.IsDefault() ? SwiftConstant(field) : "nil";
base_constructor.push_back(field_var + " = \"" + value + "\"");
}
break;
@@ -1603,14 +1567,14 @@ class SwiftGenerator : public BaseGenerator {
code_ += "{{ACCESS_TYPE}} var {{FIELDVAR}}: {{VALUETYPE}}" + nullable;
if (!field.IsOptional())
base_constructor.push_back(field_var + " = " +
field.value.constant);
SwiftConstant(field));
break;
}
if (IsEnum(field.value.type)) {
const auto default_value = IsEnum(field.value.type)
? GenEnumDefaultValue(field)
: field.value.constant;
: SwiftConstant(field);
code_ += "{{ACCESS_TYPE}} var {{FIELDVAR}}: {{VALUETYPE}}";
base_constructor.push_back(field_var + " = " + default_value);
break;
@@ -1618,10 +1582,8 @@ class SwiftGenerator : public BaseGenerator {
if (IsBool(field.value.type.base_type)) {
code_ += "{{ACCESS_TYPE}} var {{FIELDVAR}}: Bool" + nullable;
std::string default_value =
"0" == field.value.constant ? "false" : "true";
if (!field.IsOptional())
base_constructor.push_back(field_var + " = " + default_value);
base_constructor.push_back(field_var + " = " + SwiftConstant(field));
}
}
}
@@ -1676,7 +1638,7 @@ class SwiftGenerator : public BaseGenerator {
if (IsEnum(vectortype) && vectortype.base_type != BASE_TYPE_UNION) {
const auto default_value = IsEnum(field.value.type)
? GenEnumDefaultValue(field)
: field.value.constant;
: SwiftConstant(field);
buffer_constructor.push_back(indentation + field_var + ".append(_t." +
field_field + "(at: index)!)");
break;
@@ -1869,12 +1831,22 @@ class SwiftGenerator : public BaseGenerator {
}
}
std::string SwiftConstant(const FieldDef& field) {
const auto default_value =
StringIsFlatbufferNan(field.value.constant) ? ".nan" :
StringIsFlatbufferPositiveInfinity(field.value.constant) ? ".infinity" :
StringIsFlatbufferNegativeInfinity(field.value.constant) ? "-.infinity" :
IsBool(field.value.type.base_type) ? ("0" == field.value.constant ? "false" : "true") :
field.value.constant;
return default_value;
}
std::string GenEnumConstructor(const std::string &at) {
return "{{VALUETYPE}}(rawValue: " + GenReader("BASEVALUE", at) + ") ";
}
std::string ValidateFunc() {
return "static func validateVersion() { FlatBuffersVersion_22_10_25() }";
return "static func validateVersion() { FlatBuffersVersion_22_11_22() }";
}
std::string GenType(const Type &type,

View File

@@ -16,6 +16,8 @@
// independent from idl_parser, since this code is not needed for most clients
#include <algorithm>
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/flexbuffers.h"
#include "flatbuffers/idl.h"

View File

@@ -16,6 +16,7 @@
#include <algorithm>
#include <cassert>
#include <cmath>
#include <unordered_map>
#include <unordered_set>
@@ -386,8 +387,7 @@ class TsGenerator : public BaseGenerator {
return GenBBAccess() + ".__union_with_string" + arguments;
case BASE_TYPE_VECTOR: return GenGetter(type.VectorType(), arguments);
default: {
auto getter = GenBBAccess() + "." +
namer_.Method("read_" + GenType(type)) + arguments;
auto getter = GenBBAccess() + "." + "read" + GenType(type) + arguments;
if (type.base_type == BASE_TYPE_BOOL) { getter = "!!" + getter; }
return getter;
}
@@ -402,12 +402,26 @@ class TsGenerator : public BaseGenerator {
const auto &value = field.value;
if (value.type.enum_def && value.type.base_type != BASE_TYPE_UNION &&
value.type.base_type != BASE_TYPE_VECTOR) {
// If the value is an enum with a 64-bit base type, we have to just
// return the bigint value directly since typescript does not support
// enums with bigint backing types.
switch (value.type.base_type) {
case BASE_TYPE_ARRAY: {
std::string ret = "[";
for (auto i = 0; i < value.type.fixed_length; ++i) {
std::string enum_name =
AddImport(imports, *value.type.enum_def, *value.type.enum_def)
.name;
std::string enum_value = namer_.Variant(
*value.type.enum_def->FindByValue(value.constant));
ret += enum_name + "." + enum_value +
(i < value.type.fixed_length - 1 ? ", " : "");
}
ret += "]";
return ret;
}
case BASE_TYPE_LONG:
case BASE_TYPE_ULONG: {
// If the value is an enum with a 64-bit base type, we have to just
// return the bigint value directly since typescript does not support
// enums with bigint backing types.
return "BigInt('" + value.constant + "')";
}
default: {
@@ -432,6 +446,7 @@ class TsGenerator : public BaseGenerator {
return "null";
}
case BASE_TYPE_ARRAY:
case BASE_TYPE_VECTOR: return "[]";
case BASE_TYPE_LONG:
@@ -439,9 +454,16 @@ class TsGenerator : public BaseGenerator {
return "BigInt('" + value.constant + "')";
}
default:
if (value.constant == "nan") { return "NaN"; }
default: {
if (StringIsFlatbufferNan(value.constant)) {
return "NaN";
} else if (StringIsFlatbufferPositiveInfinity(value.constant)) {
return "Infinity";
} else if (StringIsFlatbufferNegativeInfinity(value.constant)) {
return "-Infinity";
}
return value.constant;
}
}
}
@@ -464,6 +486,22 @@ class TsGenerator : public BaseGenerator {
case BASE_TYPE_BOOL: return allowNull ? "boolean|null" : "boolean";
case BASE_TYPE_LONG:
case BASE_TYPE_ULONG: return allowNull ? "bigint|null" : "bigint";
case BASE_TYPE_ARRAY: {
std::string name;
if (type.element == BASE_TYPE_LONG || type.element == BASE_TYPE_ULONG) {
name = "bigint[]";
} else if (type.element != BASE_TYPE_STRUCT) {
name = "number[]";
} else {
name = "any[]";
if (parser_.opts.generate_object_based_api) {
name = "(any|" +
GetTypeName(*type.struct_def, /*object_api =*/true) + ")[]";
}
}
return name + (allowNull ? "|null" : "");
}
default:
if (IsScalar(type.base_type)) {
if (type.enum_def) {
@@ -536,12 +574,91 @@ class TsGenerator : public BaseGenerator {
// Generate arguments for a struct inside a struct. To ensure names
// don't clash, and to make it obvious these arguments are constructing
// a nested struct, prefix the name with the field name.
GenStructBody(*field.value.type.struct_def, body,
nameprefix + field.name + "_");
GenStructBody(
*field.value.type.struct_def, body,
nameprefix.length() ? nameprefix + "_" + field.name : field.name);
} else {
*body += " builder.write" + GenWriteMethod(field.value.type) + "(";
if (field.value.type.base_type == BASE_TYPE_BOOL) { *body += "+"; }
*body += nameprefix + field.name + ");\n";
auto element_type = field.value.type.element;
if (field.value.type.base_type == BASE_TYPE_ARRAY) {
switch (field.value.type.element) {
case BASE_TYPE_STRUCT: {
std::string str_last_item_idx =
NumToString(field.value.type.fixed_length - 1);
*body += "\n for (let i = " + str_last_item_idx +
"; i >= 0; --i" + ") {\n";
std::string fname = nameprefix.length()
? nameprefix + "_" + field.name
: field.name;
*body += " const item = " + fname + "?.[i];\n\n";
if (parser_.opts.generate_object_based_api) {
*body += " if (item instanceof " +
GetTypeName(*field.value.type.struct_def,
/*object_api =*/true) +
") {\n";
*body += " item.pack(builder);\n";
*body += " continue;\n";
*body += " }\n\n";
}
std::string class_name =
GetPrefixedName(*field.value.type.struct_def);
std::string pack_func_create_call =
class_name + ".create" + class_name + "(builder,\n";
pack_func_create_call +=
" " +
GenStructMemberValueTS(*field.value.type.struct_def, "item",
",\n ", false) +
"\n ";
*body += " " + pack_func_create_call;
*body += " );\n }\n\n";
break;
}
default: {
std::string str_last_item_idx =
NumToString(field.value.type.fixed_length - 1);
std::string fname = nameprefix.length()
? nameprefix + "_" + field.name
: field.name;
*body += "\n for (let i = " + str_last_item_idx +
"; i >= 0; --i) {\n";
*body += " builder.write";
*body += GenWriteMethod(
static_cast<flatbuffers::Type>(field.value.type.element));
*body += "(";
*body += element_type == BASE_TYPE_BOOL ? "+" : "";
if (element_type == BASE_TYPE_LONG ||
element_type == BASE_TYPE_ULONG) {
*body += "BigInt(" + fname + "?.[i] ?? 0));\n";
} else {
*body += "(" + fname + "?.[i] ?? 0));\n\n";
}
*body += " }\n\n";
break;
}
}
} else {
std::string fname =
nameprefix.length() ? nameprefix + "_" + field.name : field.name;
*body += " builder.write" + GenWriteMethod(field.value.type) + "(";
if (field.value.type.base_type == BASE_TYPE_BOOL) {
*body += "Number(Boolean(" + fname + ")));\n";
continue;
} else if (field.value.type.base_type == BASE_TYPE_LONG ||
field.value.type.base_type == BASE_TYPE_ULONG) {
*body += "BigInt(" + fname + " ?? 0));\n";
continue;
}
*body += fname + ");\n";
}
}
}
}
@@ -916,7 +1033,10 @@ class TsGenerator : public BaseGenerator {
const auto conversion_function = GenUnionListConvFuncName(enum_def);
ret = "(() => {\n";
ret += " const ret = [];\n";
ret += " const ret: (" +
GenObjApiUnionTypeTS(imports, *union_type.struct_def,
parser_.opts, *union_type.enum_def) +
")[] = [];\n";
ret += " for(let targetEnumIndex = 0; targetEnumIndex < this." +
namer_.Method(field_name, "TypeLength") + "()" +
"; "
@@ -973,6 +1093,11 @@ class TsGenerator : public BaseGenerator {
std::string nullValue = "0";
if (field.value.type.base_type == BASE_TYPE_BOOL) {
nullValue = "false";
} else if (field.value.type.base_type == BASE_TYPE_LONG ||
field.value.type.base_type == BASE_TYPE_ULONG) {
nullValue = "BigInt(0)";
} else if (field.value.type.base_type == BASE_TYPE_ARRAY) {
nullValue = "[]";
}
ret += "(" + curr_member_accessor + " ?? " + nullValue + ")";
} else {
@@ -1091,6 +1216,95 @@ class TsGenerator : public BaseGenerator {
break;
}
case BASE_TYPE_ARRAY: {
auto vectortype = field.value.type.VectorType();
auto vectortypename =
GenTypeName(imports, struct_def, vectortype, false);
is_vector = true;
field_type = "(";
switch (vectortype.base_type) {
case BASE_TYPE_STRUCT: {
const auto &sd = *field.value.type.struct_def;
const auto field_type_name =
GetTypeName(sd, /*object_api=*/true);
field_type += field_type_name;
field_type += ")[]";
field_val = GenBBAccess() + ".createObjList<" + vectortypename +
", " + field_type_name + ">(" +
field_binded_method + ", " +
NumToString(field.value.type.fixed_length) + ")";
if (sd.fixed) {
field_offset_decl =
"builder.createStructOffsetList(this." + field_field +
", " + AddImport(imports, struct_def, struct_def).name +
"." + namer_.Method("start", field, "Vector") + ")";
} else {
field_offset_decl =
AddImport(imports, struct_def, struct_def).name + "." +
namer_.Method("create", field, "Vector") +
"(builder, builder.createObjectOffsetList(" + "this." +
field_field + "))";
}
break;
}
case BASE_TYPE_STRING: {
field_type += "string)[]";
field_val = GenBBAccess() + ".createScalarList<string>(" +
field_binded_method + ", this." +
namer_.Field(field, "Length") + "())";
field_offset_decl =
AddImport(imports, struct_def, struct_def).name + "." +
namer_.Method("create", field, "Vector") +
"(builder, builder.createObjectOffsetList(" + "this." +
namer_.Field(field) + "))";
break;
}
case BASE_TYPE_UNION: {
field_type += GenObjApiUnionTypeTS(
imports, struct_def, parser.opts, *(vectortype.enum_def));
field_type += ")[]";
field_val = GenUnionValTS(imports, struct_def, field_method,
vectortype, true);
field_offset_decl =
AddImport(imports, struct_def, struct_def).name + "." +
namer_.Method("create", field, "Vector") +
"(builder, builder.createObjectOffsetList(" + "this." +
namer_.Field(field) + "))";
break;
}
default: {
if (vectortype.enum_def) {
field_type += GenTypeName(imports, struct_def, vectortype,
false, HasNullDefault(field));
} else {
field_type += vectortypename;
}
field_type += ")[]";
field_val = GenBBAccess() + ".createScalarList<" +
vectortypename + ">(" + field_binded_method + ", " +
NumToString(field.value.type.fixed_length) + ")";
field_offset_decl =
AddImport(imports, struct_def, struct_def).name + "." +
namer_.Method("create", field, "Vector") +
"(builder, this." + field_field + ")";
break;
}
}
break;
}
case BASE_TYPE_VECTOR: {
auto vectortype = field.value.type.VectorType();
auto vectortypename =
@@ -1344,9 +1558,16 @@ class TsGenerator : public BaseGenerator {
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
if (field.deprecated) continue;
auto offset_prefix =
" const offset = " + GenBBAccess() + ".__offset(this.bb_pos, " +
NumToString(field.value.offset) + ");\n return offset ? ";
std::string offset_prefix = "";
if (field.value.type.base_type == BASE_TYPE_ARRAY) {
offset_prefix = " return ";
} else {
offset_prefix = " const offset = " + GenBBAccess() +
".__offset(this.bb_pos, " +
NumToString(field.value.offset) + ");\n";
offset_prefix += " return offset ? ";
}
// Emit a scalar field
const auto is_string = IsString(field.value.type);
@@ -1386,9 +1607,11 @@ class TsGenerator : public BaseGenerator {
} else {
std::string index = "this.bb_pos + offset";
if (is_string) { index += ", optionalEncoding"; }
code += offset_prefix +
GenGetter(field.value.type, "(" + index + ")") + " : " +
GenDefaultValue(field, imports);
code +=
offset_prefix + GenGetter(field.value.type, "(" + index + ")");
if (field.value.type.base_type != BASE_TYPE_ARRAY) {
code += " : " + GenDefaultValue(field, imports);
}
code += ";\n";
}
}
@@ -1421,6 +1644,95 @@ class TsGenerator : public BaseGenerator {
break;
}
case BASE_TYPE_ARRAY: {
auto vectortype = field.value.type.VectorType();
auto vectortypename =
GenTypeName(imports, struct_def, vectortype, false);
auto inline_size = InlineSize(vectortype);
auto index = "this.bb_pos + " + NumToString(field.value.offset) +
" + index" + MaybeScale(inline_size);
std::string ret_type;
bool is_union = false;
switch (vectortype.base_type) {
case BASE_TYPE_STRUCT: ret_type = vectortypename; break;
case BASE_TYPE_STRING: ret_type = vectortypename; break;
case BASE_TYPE_UNION:
ret_type = "?flatbuffers.Table";
is_union = true;
break;
default: ret_type = vectortypename;
}
GenDocComment(field.doc_comment, code_ptr);
std::string prefix = namer_.Method(field);
// TODO: make it work without any
// if (is_union) { prefix += "<T extends flatbuffers.Table>"; }
if (is_union) { prefix += ""; }
prefix += "(index: number";
if (is_union) {
const auto union_type =
GenUnionGenericTypeTS(*(field.value.type.enum_def));
vectortypename = union_type;
code += prefix + ", obj:" + union_type;
} else if (vectortype.base_type == BASE_TYPE_STRUCT) {
code += prefix + ", obj?:" + vectortypename;
} else if (IsString(vectortype)) {
code += prefix + "):string\n";
code += prefix + ",optionalEncoding:flatbuffers.Encoding" +
"):" + vectortypename + "\n";
code += prefix + ",optionalEncoding?:any";
} else {
code += prefix;
}
code += "):" + vectortypename + "|null {\n";
if (vectortype.base_type == BASE_TYPE_STRUCT) {
code += offset_prefix + "(obj || " +
GenerateNewExpression(vectortypename);
code += ").__init(";
code += vectortype.struct_def->fixed
? index
: GenBBAccess() + ".__indirect(" + index + ")";
code += ", " + GenBBAccess() + ")";
} else {
if (is_union) {
index = "obj, " + index;
} else if (IsString(vectortype)) {
index += ", optionalEncoding";
}
code += offset_prefix + GenGetter(vectortype, "(" + index + ")");
}
switch (field.value.type.base_type) {
case BASE_TYPE_ARRAY: {
break;
}
case BASE_TYPE_BOOL: {
code += " : false";
break;
}
case BASE_TYPE_LONG:
case BASE_TYPE_ULONG: {
code += " : BigInt(0)";
break;
}
default: {
if (IsScalar(field.value.type.element)) {
if (field.value.type.enum_def) {
code += field.value.constant;
} else {
code += " : 0";
}
} else {
code += ": null";
}
break;
}
}
code += ";\n";
break;
}
case BASE_TYPE_VECTOR: {
auto vectortype = field.value.type.VectorType();
auto vectortypename =

View File

@@ -483,6 +483,7 @@ CheckedError Parser::SkipByteOrderMark() {
CheckedError Parser::Next() {
doc_comment_.clear();
prev_cursor_ = cursor_;
bool seen_newline = cursor_ == source_;
attribute_.clear();
attr_is_trivial_ascii_string_ = true;
@@ -507,6 +508,8 @@ CheckedError Parser::Next() {
case ')':
case '[':
case ']':
case '<':
case '>':
case ',':
case ':':
case ';':
@@ -1055,8 +1058,12 @@ CheckedError Parser::ParseField(StructDef &struct_def) {
if (field->key) {
if (struct_def.has_key) return Error("only one field may be set as 'key'");
struct_def.has_key = true;
if (!IsScalar(type.base_type) && !IsString(type)) {
return Error("'key' field must be string or scalar type");
auto is_valid = IsScalar(type.base_type) || IsString(type);
if (IsArray(type)) { is_valid |= IsScalar(type.VectorType().base_type); }
if (!is_valid) {
return Error(
"'key' field must be string, scalar type or fixed size array of "
"scalars");
}
}
@@ -1500,7 +1507,7 @@ CheckedError Parser::ParseTable(const StructDef &struct_def, std::string *value,
if (!struct_def.sortbysize ||
size == SizeOf(field_value.type.base_type)) {
switch (field_value.type.base_type) {
// clang-format off
// clang-format off
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \
case BASE_TYPE_ ## ENUM: \
builder_.Pad(field->padding); \
@@ -1629,7 +1636,7 @@ CheckedError Parser::ParseVector(const Type &type, uoffset_t *ovalue,
// start at the back, since we're building the data backwards.
auto &val = field_stack_.back().first;
switch (val.type.base_type) {
// clang-format off
// clang-format off
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE,...) \
case BASE_TYPE_ ## ENUM: \
if (IsStruct(val.type)) SerializeStruct(*val.type.struct_def, val); \
@@ -2265,8 +2272,12 @@ template<typename T> void EnumDef::ChangeEnumValue(EnumVal *ev, T new_value) {
}
namespace EnumHelper {
template<BaseType E> struct EnumValType { typedef int64_t type; };
template<> struct EnumValType<BASE_TYPE_ULONG> { typedef uint64_t type; };
template<BaseType E> struct EnumValType {
typedef int64_t type;
};
template<> struct EnumValType<BASE_TYPE_ULONG> {
typedef uint64_t type;
};
} // namespace EnumHelper
struct EnumValBuilder {
@@ -2581,7 +2592,7 @@ bool Parser::SupportsAdvancedArrayFeatures() const {
return (opts.lang_to_generate &
~(IDLOptions::kCpp | IDLOptions::kPython | IDLOptions::kJava |
IDLOptions::kCSharp | IDLOptions::kJsonSchema | IDLOptions::kJson |
IDLOptions::kBinary | IDLOptions::kRust)) == 0;
IDLOptions::kBinary | IDLOptions::kRust | IDLOptions::kTs)) == 0;
}
Namespace *Parser::UniqueNamespace(Namespace *ns) {
@@ -2896,6 +2907,8 @@ CheckedError Parser::ParseProtoFields(StructDef *struct_def, bool isextend,
NEXT();
while (!Is(';')) { NEXT(); } // A variety of formats, just skip.
NEXT();
} else if (IsIdent("map")) {
ECHECK(ParseProtoMapField(struct_def));
} else {
std::vector<std::string> field_comment = doc_comment_;
// Parse the qualifier.
@@ -3030,6 +3043,41 @@ CheckedError Parser::ParseProtoFields(StructDef *struct_def, bool isextend,
return NoError();
}
CheckedError Parser::ParseProtoMapField(StructDef *struct_def) {
NEXT();
EXPECT('<');
Type key_type;
ECHECK(ParseType(key_type));
EXPECT(',');
Type value_type;
ECHECK(ParseType(value_type));
EXPECT('>');
auto field_name = attribute_;
NEXT();
EXPECT('=');
EXPECT(kTokenIntegerConstant);
EXPECT(';');
auto entry_table_name = ConvertCase(field_name, Case::kUpperCamel) + "Entry";
StructDef *entry_table;
ECHECK(StartStruct(entry_table_name, &entry_table));
entry_table->has_key = true;
FieldDef *key_field;
ECHECK(AddField(*entry_table, "key", key_type, &key_field));
key_field->key = true;
FieldDef *value_field;
ECHECK(AddField(*entry_table, "value", value_type, &value_field));
Type field_type;
field_type.base_type = BASE_TYPE_VECTOR;
field_type.element = BASE_TYPE_STRUCT;
field_type.struct_def = entry_table;
FieldDef *field;
ECHECK(AddField(*struct_def, field_name, field_type, &field));
return NoError();
}
CheckedError Parser::ParseProtoKey() {
if (token_ == '(') {
NEXT();
@@ -3264,6 +3312,10 @@ bool Parser::ParseJson(const char *json, const char *json_filename) {
return done;
}
std::ptrdiff_t Parser::BytesConsumed() const {
return std::distance(source_, prev_cursor_);
}
CheckedError Parser::StartParseFile(const char *source,
const char *source_filename) {
file_being_parsed_ = source_filename ? source_filename : "";
@@ -3601,9 +3653,11 @@ CheckedError Parser::DoParseJson() {
: nullptr);
}
}
// Check that JSON file doesn't contain more objects or IDL directives.
// Comments after JSON are allowed.
EXPECT(kTokenEof);
if (opts.require_json_eof) {
// Check that JSON file doesn't contain more objects or IDL directives.
// Comments after JSON are allowed.
EXPECT(kTokenEof);
}
return NoError();
}
@@ -3753,7 +3807,7 @@ Offset<reflection::Object> StructDef::Serialize(FlatBufferBuilder *builder,
const auto name__ = builder->CreateString(qualified_name);
const auto flds__ = builder->CreateVectorOfSortedTables(&field_offsets);
const auto attr__ = SerializeAttributes(builder, parser);
const auto docs__ = parser.opts.binary_schema_comments
const auto docs__ = parser.opts.binary_schema_comments && !doc_comment.empty()
? builder->CreateVectorOfStrings(doc_comment)
: 0;
std::string decl_file_in_project = declaration_file ? *declaration_file : "";
@@ -3811,7 +3865,7 @@ Offset<reflection::Field> FieldDef::Serialize(FlatBufferBuilder *builder,
auto name__ = builder->CreateString(name);
auto type__ = value.type.Serialize(builder);
auto attr__ = SerializeAttributes(builder, parser);
auto docs__ = parser.opts.binary_schema_comments
auto docs__ = parser.opts.binary_schema_comments && !doc_comment.empty()
? builder->CreateVectorOfStrings(doc_comment)
: 0;
double d;
@@ -3864,7 +3918,7 @@ Offset<reflection::RPCCall> RPCCall::Serialize(FlatBufferBuilder *builder,
const Parser &parser) const {
auto name__ = builder->CreateString(name);
auto attr__ = SerializeAttributes(builder, parser);
auto docs__ = parser.opts.binary_schema_comments
auto docs__ = parser.opts.binary_schema_comments && !doc_comment.empty()
? builder->CreateVectorOfStrings(doc_comment)
: 0;
return reflection::CreateRPCCall(
@@ -3892,7 +3946,7 @@ Offset<reflection::Service> ServiceDef::Serialize(FlatBufferBuilder *builder,
const auto name__ = builder->CreateString(qualified_name);
const auto call__ = builder->CreateVector(servicecall_offsets);
const auto attr__ = SerializeAttributes(builder, parser);
const auto docs__ = parser.opts.binary_schema_comments
const auto docs__ = parser.opts.binary_schema_comments && !doc_comment.empty()
? builder->CreateVectorOfStrings(doc_comment)
: 0;
std::string decl_file_in_project = declaration_file ? *declaration_file : "";
@@ -3930,7 +3984,7 @@ Offset<reflection::Enum> EnumDef::Serialize(FlatBufferBuilder *builder,
const auto vals__ = builder->CreateVector(enumval_offsets);
const auto type__ = underlying_type.Serialize(builder);
const auto attr__ = SerializeAttributes(builder, parser);
const auto docs__ = parser.opts.binary_schema_comments
const auto docs__ = parser.opts.binary_schema_comments && !doc_comment.empty()
? builder->CreateVectorOfStrings(doc_comment)
: 0;
std::string decl_file_in_project = declaration_file ? *declaration_file : "";
@@ -3975,7 +4029,7 @@ Offset<reflection::EnumVal> EnumVal::Serialize(FlatBufferBuilder *builder,
const auto name__ = builder->CreateString(name);
const auto type__ = union_type.Serialize(builder);
const auto attr__ = SerializeAttributes(builder, parser);
const auto docs__ = parser.opts.binary_schema_comments
const auto docs__ = parser.opts.binary_schema_comments && !doc_comment.empty()
? builder->CreateVectorOfStrings(doc_comment)
: 0;
return reflection::CreateEnumVal(*builder, name__, value, type__, docs__,

View File

@@ -196,7 +196,7 @@ class Namer {
result += ConvertCase(*d, config_.directories, Case::kUpperCamel);
result.push_back(kPathSeparator);
}
if (skip_trailing_seperator) result.pop_back();
if (skip_trailing_seperator && !result.empty()) result.pop_back();
return result;
}

View File

@@ -119,4 +119,4 @@ extension UInt64: Scalar, Verifiable {
public typealias NumericValue = UInt64
}
public func FlatBuffersVersion_22_10_25() {}
public func FlatBuffersVersion_22_11_22() {}

View File

@@ -2,7 +2,7 @@
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 22.10.25
flatc version: 22.11.22
Declared by :
]#

View File

@@ -22,6 +22,9 @@ cc_test(
"is_quiet_nan.h",
"json_test.cpp",
"json_test.h",
"key_field/key_field_sample_generated.h",
"key_field_test.cpp",
"key_field_test.h",
"monster_test.cpp",
"monster_test.h",
"monster_test_bfbs_generated.h",
@@ -63,6 +66,7 @@ cc_test(
":evolution_test/evolution_v2.json",
":include_test/include_test1.fbs",
":include_test/sub/include_test2.fbs",
":key_field/key_field_sample.fbs",
":monster_extra.fbs",
":monster_test.bfbs",
":monster_test.fbs",

View File

@@ -20,6 +20,9 @@ command -v dart >/dev/null 2>&1 || { echo >&2 "Dart tests require dart to be in
# output required files to the dart folder so that pub will be able to
# distribute them and more people can more easily run the dart tests
../flatc --dart --gen-object-api -I include_test -o ../dart/test monster_test.fbs
../flatc --dart --gen-object-api -I include_test/sub -o ../dart/test include_test/include_test1.fbs
../flatc --dart --gen-object-api -I include_test -o ../dart/test include_test/sub/include_test2.fbs
cp monsterdata_test.mon ../dart/test
cp monster_test.fbs ../dart/test

View File

@@ -9,7 +9,7 @@ import com.google.flatbuffers.*;
@SuppressWarnings("unused")
public final class LongFloatEntry extends Table {
public static void ValidateVersion() { Constants.FLATBUFFERS_22_10_25(); }
public static void ValidateVersion() { Constants.FLATBUFFERS_22_11_22(); }
public static LongFloatEntry getRootAsLongFloatEntry(ByteBuffer _bb) { return getRootAsLongFloatEntry(_bb, new LongFloatEntry()); }
public static LongFloatEntry getRootAsLongFloatEntry(ByteBuffer _bb, LongFloatEntry obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }

View File

@@ -32,7 +32,7 @@ class LongFloatEntry : Table() {
return (val_1 - val_2).sign
}
companion object {
fun validateVersion() = Constants.FLATBUFFERS_22_10_25()
fun validateVersion() = Constants.FLATBUFFERS_22_11_22()
fun getRootAsLongFloatEntry(_bb: ByteBuffer): LongFloatEntry = getRootAsLongFloatEntry(_bb, LongFloatEntry())
fun getRootAsLongFloatEntry(_bb: ByteBuffer, obj: LongFloatEntry): LongFloatEntry {
_bb.order(ByteOrder.LITTLE_ENDIAN)

View File

@@ -9,7 +9,7 @@ import com.google.flatbuffers.*;
@SuppressWarnings("unused")
public final class LongFloatMap extends Table {
public static void ValidateVersion() { Constants.FLATBUFFERS_22_10_25(); }
public static void ValidateVersion() { Constants.FLATBUFFERS_22_11_22(); }
public static LongFloatMap getRootAsLongFloatMap(ByteBuffer _bb) { return getRootAsLongFloatMap(_bb, new LongFloatMap()); }
public static LongFloatMap getRootAsLongFloatMap(ByteBuffer _bb, LongFloatMap obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }

View File

@@ -46,7 +46,7 @@ class LongFloatMap : Table() {
}
}
companion object {
fun validateVersion() = Constants.FLATBUFFERS_22_10_25()
fun validateVersion() = Constants.FLATBUFFERS_22_11_22()
fun getRootAsLongFloatMap(_bb: ByteBuffer): LongFloatMap = getRootAsLongFloatMap(_bb, LongFloatMap())
fun getRootAsLongFloatMap(_bb: ByteBuffer, obj: LongFloatMap): LongFloatMap {
_bb.order(ByteOrder.LITTLE_ENDIAN)

View File

@@ -20,26 +20,18 @@ go_path=${test_dir}/go_gen
go_src=${go_path}/src
# Emit Go code for the example schemas in the test dir:
../flatc -g --gen-object-api -I include_test monster_test.fbs optional_scalars.fbs
../flatc -g --gen-object-api -I include_test -o ${go_src} monster_test.fbs optional_scalars.fbs
../flatc -g --gen-object-api -I include_test/sub -o ${go_src} include_test/order.fbs
../flatc -g --gen-object-api -o ${go_src}/Pizza include_test/sub/no_namespace.fbs
# Go requires a particular layout of files in order to link multiple packages.
# Copy flatbuffer Go files to their own package directories to compile the
# test binary:
mkdir -p ${go_src}/MyGame/Example
mkdir -p ${go_src}/MyGame/Example2
mkdir -p ${go_src}/github.com/google/flatbuffers/go
mkdir -p ${go_src}/flatbuffers_test
mkdir -p ${go_src}/optional_scalars
cp -a MyGame/*.go ./go_gen/src/MyGame/
cp -a MyGame/Example/*.go ./go_gen/src/MyGame/Example/
cp -a MyGame/Example2/*.go ./go_gen/src/MyGame/Example2/
# do not compile the gRPC generated files, which are not tested by go_test.go
# below, but have their own test.
rm ./go_gen/src/MyGame/Example/*_grpc.go
cp -a ../go/* ./go_gen/src/github.com/google/flatbuffers/go
cp -a ./go_test.go ./go_gen/src/flatbuffers_test/
cp -a optional_scalars/*.go ./go_gen/src/optional_scalars
# https://stackoverflow.com/a/63545857/7024978
# We need to turn off go modules for this script
@@ -72,7 +64,7 @@ else
exit 1
fi
NOT_FMT_FILES=$(gofmt -l MyGame)
NOT_FMT_FILES=$(gofmt -l .)
if [[ ${NOT_FMT_FILES} != "" ]]; then
echo "These files are not well gofmt'ed:"
echo
@@ -80,3 +72,6 @@ if [[ ${NOT_FMT_FILES} != "" ]]; then
# enable this when enums are properly formated
# exit 1
fi
# Re-enable go modules when done tests
go env -w GO111MODULE=on

View File

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

View File

@@ -2,7 +2,7 @@
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 22.10.25
flatc version: 22.11.22
Declared by :
]#

View File

@@ -3,7 +3,7 @@
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 22.10.25
flatc version: 22.11.22
Declared by : //monster_test.fbs
Rooting type : MyGame.Example.Monster (//monster_test.fbs)

View File

@@ -2,7 +2,7 @@
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 22.10.25
flatc version: 22.11.22
Declared by :
Rooting type : MyGame.Example.Monster ()

View File

@@ -38,11 +38,15 @@ class AbilityT(object):
@classmethod
def InitFromBuf(cls, buf, pos):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, 0)
ability = Ability()
ability.Init(buf, pos+n)
ability.Init(buf, pos)
return cls.InitFromObj(ability)
@classmethod
def InitFromPackedBuf(cls, buf, pos=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos)
return cls.InitFromBuf(buf, pos+n)
@classmethod
def InitFromObj(cls, ability):
x = AbilityT()

View File

@@ -4,7 +4,6 @@ package Example
import (
"strconv"
flatbuffers "github.com/google/flatbuffers/go"
MyGame__Example2 "MyGame/Example2"
@@ -63,13 +62,16 @@ func (t *AnyT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
func (rcv Any) UnPack(table flatbuffers.Table) *AnyT {
switch rcv {
case AnyMonster:
x := Monster{_tab: table}
var x Monster
x.Init(table.Bytes, table.Pos)
return &AnyT{ Type: AnyMonster, Value: x.UnPack() }
case AnyTestSimpleTableWithEnum:
x := TestSimpleTableWithEnum{_tab: table}
var x TestSimpleTableWithEnum
x.Init(table.Bytes, table.Pos)
return &AnyT{ Type: AnyTestSimpleTableWithEnum, Value: x.UnPack() }
case AnyMyGame_Example2_Monster:
x := Monster{_tab: table}
var x MyGame__Example2.Monster
x.Init(table.Bytes, table.Pos)
return &AnyT{ Type: AnyMyGame_Example2_Monster, Value: x.UnPack() }
}
return nil

View File

@@ -3,7 +3,7 @@
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 22.10.25
flatc version: 22.11.22
Declared by : //monster_test.fbs
Rooting type : MyGame.Example.Monster (//monster_test.fbs)

View File

@@ -2,7 +2,7 @@
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 22.10.25
flatc version: 22.11.22
Declared by :
Rooting type : MyGame.Example.Monster ()

View File

@@ -4,7 +4,6 @@ package Example
import (
"strconv"
flatbuffers "github.com/google/flatbuffers/go"
)
@@ -61,13 +60,16 @@ func (t *AnyAmbiguousAliasesT) Pack(builder *flatbuffers.Builder) flatbuffers.UO
func (rcv AnyAmbiguousAliases) UnPack(table flatbuffers.Table) *AnyAmbiguousAliasesT {
switch rcv {
case AnyAmbiguousAliasesM1:
x := Monster{_tab: table}
var x Monster
x.Init(table.Bytes, table.Pos)
return &AnyAmbiguousAliasesT{ Type: AnyAmbiguousAliasesM1, Value: x.UnPack() }
case AnyAmbiguousAliasesM2:
x := Monster{_tab: table}
var x Monster
x.Init(table.Bytes, table.Pos)
return &AnyAmbiguousAliasesT{ Type: AnyAmbiguousAliasesM2, Value: x.UnPack() }
case AnyAmbiguousAliasesM3:
x := Monster{_tab: table}
var x Monster
x.Init(table.Bytes, table.Pos)
return &AnyAmbiguousAliasesT{ Type: AnyAmbiguousAliasesM3, Value: x.UnPack() }
}
return nil

View File

@@ -3,7 +3,7 @@
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 22.10.25
flatc version: 22.11.22
Declared by : //monster_test.fbs
Rooting type : MyGame.Example.Monster (//monster_test.fbs)

View File

@@ -2,7 +2,7 @@
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 22.10.25
flatc version: 22.11.22
Declared by :
Rooting type : MyGame.Example.Monster ()

View File

@@ -4,7 +4,6 @@ package Example
import (
"strconv"
flatbuffers "github.com/google/flatbuffers/go"
MyGame__Example2 "MyGame/Example2"
@@ -63,13 +62,16 @@ func (t *AnyUniqueAliasesT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffs
func (rcv AnyUniqueAliases) UnPack(table flatbuffers.Table) *AnyUniqueAliasesT {
switch rcv {
case AnyUniqueAliasesM:
x := Monster{_tab: table}
var x Monster
x.Init(table.Bytes, table.Pos)
return &AnyUniqueAliasesT{ Type: AnyUniqueAliasesM, Value: x.UnPack() }
case AnyUniqueAliasesTS:
x := TestSimpleTableWithEnum{_tab: table}
var x TestSimpleTableWithEnum
x.Init(table.Bytes, table.Pos)
return &AnyUniqueAliasesT{ Type: AnyUniqueAliasesTS, Value: x.UnPack() }
case AnyUniqueAliasesM2:
x := Monster{_tab: table}
var x MyGame__Example2.Monster
x.Init(table.Bytes, table.Pos)
return &AnyUniqueAliasesT{ Type: AnyUniqueAliasesM2, Value: x.UnPack() }
}
return nil

View File

@@ -3,7 +3,7 @@
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 22.10.25
flatc version: 22.11.22
Declared by : //monster_test.fbs
Rooting type : MyGame.Example.Monster (//monster_test.fbs)

View File

@@ -2,7 +2,7 @@
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 22.10.25
flatc version: 22.11.22
Declared by :
Rooting type : MyGame.Example.Monster ()

View File

@@ -123,11 +123,15 @@ class ArrayStructT(object):
@classmethod
def InitFromBuf(cls, buf, pos):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, 0)
arrayStruct = ArrayStruct()
arrayStruct.Init(buf, pos+n)
arrayStruct.Init(buf, pos)
return cls.InitFromObj(arrayStruct)
@classmethod
def InitFromPackedBuf(cls, buf, pos=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos)
return cls.InitFromBuf(buf, pos+n)
@classmethod
def InitFromObj(cls, arrayStruct):
x = ArrayStructT()

View File

@@ -13,7 +13,7 @@ public struct ArrayTable : IFlatbufferObject
{
private Table __p;
public ByteBuffer ByteBuffer { get { return __p.bb; } }
public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_22_10_25(); }
public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_22_11_22(); }
public static ArrayTable GetRootAsArrayTable(ByteBuffer _bb) { return GetRootAsArrayTable(_bb, new ArrayTable()); }
public static ArrayTable GetRootAsArrayTable(ByteBuffer _bb, ArrayTable obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); }
public static bool ArrayTableBufferHasIdentifier(ByteBuffer _bb) { return Table.__has_identifier(_bb, "ARRT"); }

View File

@@ -9,7 +9,7 @@ import com.google.flatbuffers.*;
@SuppressWarnings("unused")
public final class ArrayTable extends Table {
public static void ValidateVersion() { Constants.FLATBUFFERS_22_10_25(); }
public static void ValidateVersion() { Constants.FLATBUFFERS_22_11_22(); }
public static ArrayTable getRootAsArrayTable(ByteBuffer _bb) { return getRootAsArrayTable(_bb, new ArrayTable()); }
public static ArrayTable getRootAsArrayTable(ByteBuffer _bb, ArrayTable obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public static boolean ArrayTableBufferHasIdentifier(ByteBuffer _bb) { return __has_identifier(_bb, "ARRT"); }

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