Compare commits

...

37 Commits

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

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

* Fix incorrect import statements

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

* Fix $PYTHONPATH in PythonTest.sh

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

* PythonTest: fail if something goes wrong

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

* Build flatc for Python tests

* Regenerate codes

---------

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

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

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

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

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

* add static to functions

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

* Made vector_downward work on 64 bit types

* vector_downward uses size_t, added offset64 to reflection

* cleaned up adding offset64 in parser

* Add C++ testing skeleton for 64-bit

* working test for CreateVector64

* working >2 GiB buffers

* support for large strings

* simplified CreateString<> to just provide the offset type

* generalize CreateVector template

* update test_64.afb due to upstream format change

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

* Switch to Offset64 for Vector64

* Update for reflection bfbs output change

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

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

* Support for 32-vector with 64-addressing

* Vector64 basic builder + tests working

* basic support for json vector64 support

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

* working C++ vector64 builder

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

* Enable Vector64 for --annotate-sparse-vectors

* Merged from upstream

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

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

* move template<> outside class body for GCC

* update run.sh to build and run tests

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

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

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

* fixed CreateDirect method by iterating by Offset64 first

* internal refactoring of flatbufferbuilder

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

* evolution tests for adding a vector64 field

* conformity tests for adding/removing offset64 attributes

* ensure test is for a big buffer

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

* add missing static that GCC only complains about

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

* move 64-bit CalculateOffset internal

* fixed return size of EndVector

* various fixes on windows

* add SizeT to vector_downward

* minimze range of size changes in vector and builder

* reworked how tracking if 64-offsets are added

* Add ReturnT to EndVector

* small cleanups

* remove need for second Array definition

* combine IndirectHelpers into one definition

* started support for vector of struct

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

* small cleanups

* add verification for vector64

* add sized prefix for 64-bit buffers

* add fuzzer for 64-bit

* add example of adding many vectors using a wrapper table

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

* remove run.sh and fix cmakelist issue

* fixed bazel rules

* fixed some PR comments

* add 64-bit tests to cmakelist
2023-05-09 09:16:30 -07:00
326 changed files with 7547 additions and 3879 deletions

1
.github/labeler.yml vendored
View File

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

View File

@@ -76,6 +76,28 @@ jobs:
- name: build - name: build
run: make -j run: make -j
build-linux-out-of-source:
name: Build Linux with out-of-source build location
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: make build directory
run: mkdir build
- name: cmake
working-directory: build
run: >
CXX=clang++-12 cmake .. -G "Unix Makefiles" -DFLATBUFFERS_STRICT_MODE=ON
-DFLATBUFFERS_BUILD_CPP17=ON -DFLATBUFFERS_CPP_STD=17
- name: build
working-directory: build
run: make -j
- name: test
working-directory: build
run: pwd && ./flattests
- name: test C++17
working-directory: build
run: ./flattests_cpp17
build-linux-cpp-std: build-linux-cpp-std:
name: Build Linux C++ name: Build Linux C++
runs-on: ubuntu-latest runs-on: ubuntu-latest
@@ -422,8 +444,8 @@ jobs:
# gradlew # gradlew
run: gradle jvmMainClasses jvmTest jsTest jsBrowserTest run: gradle jvmMainClasses jvmTest jsTest jsBrowserTest
build-rust: build-rust-linux:
name: Build Rust name: Build Rust Linux
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v3
@@ -431,11 +453,23 @@ jobs:
working-directory: tests working-directory: tests
run: bash RustTest.sh run: bash RustTest.sh
build-rust-windows:
name: Build Rust Windows
runs-on: windows-2019
steps:
- uses: actions/checkout@v3
- name: test
working-directory: tests
run: ./RustTest.bat
build-python: build-python:
name: Build Python name: Build Python
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v3
- name: flatc
# FIXME: make test script not rely on flatc
run: cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_INSTALL=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF -DFLATBUFFERS_STRICT_MODE=ON . && make -j
- name: test - name: test
working-directory: tests working-directory: tests
run: bash PythonTest.sh run: bash PythonTest.sh

View File

@@ -4,6 +4,15 @@ All major or breaking changes will be documented in this file, as well as any
new features that should be highlighted. Minor fixes or improvements are not new features that should be highlighted. Minor fixes or improvements are not
necessarily listed. necessarily listed.
## [23.5.26 (May 26 2023)](https://github.com/google/flatbuffers/releases/tag/v23.5.26)
* Mostly bug fixing for 64-bit support
* Adds support for specifying underling type of unions in C++ and TS/JS (#7954)
## [23.5.9 (May 9 2023)](https://github.com/google/flatbuffers/releases/tag/v23.5.9)
* 64-bit support for C++ (#7935)
## [23.5.8 (May 8 2023)](https://github.com/google/flatbuffers/releases/tag/v23.5.8) ## [23.5.8 (May 8 2023)](https://github.com/google/flatbuffers/releases/tag/v23.5.8)
* add key_field to compiled tests * add key_field to compiled tests

View File

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

View File

@@ -166,7 +166,6 @@ set(FlatBuffers_Compiler_SRCS
src/idl_gen_php.cpp src/idl_gen_php.cpp
src/idl_gen_python.cpp src/idl_gen_python.cpp
src/idl_gen_lobster.cpp src/idl_gen_lobster.cpp
src/idl_gen_lua.cpp
src/idl_gen_rust.cpp src/idl_gen_rust.cpp
src/idl_gen_fbs.cpp src/idl_gen_fbs.cpp
src/idl_gen_grpc.cpp src/idl_gen_grpc.cpp
@@ -234,6 +233,8 @@ set(FlatBuffers_Tests_SRCS
tests/native_type_test_impl.cpp tests/native_type_test_impl.cpp
tests/alignment_test.h tests/alignment_test.h
tests/alignment_test.cpp tests/alignment_test.cpp
tests/64bit/offset64_test.h
tests/64bit/offset64_test.cpp
include/flatbuffers/code_generators.h include/flatbuffers/code_generators.h
src/code_generators.cpp src/code_generators.cpp
) )
@@ -246,7 +247,6 @@ set(FlatBuffers_Tests_CPP17_SRCS
) )
set(FlatBuffers_Sample_Binary_SRCS set(FlatBuffers_Sample_Binary_SRCS
include/flatbuffers/flatbuffers.h
samples/sample_binary.cpp samples/sample_binary.cpp
) )
@@ -490,12 +490,13 @@ endif()
function(compile_schema SRC_FBS OPT OUT_GEN_FILE) function(compile_schema SRC_FBS OPT OUT_GEN_FILE)
get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH) get_filename_component(SRC_FBS_DIR ${SRC_FBS} PATH)
string(REGEX REPLACE "\\.fbs$" "_generated.h" GEN_HEADER ${SRC_FBS}) string(REGEX REPLACE "\\.fbs$" "_generated.h" GEN_HEADER ${SRC_FBS})
add_custom_command(TARGET flatc POST_BUILD add_custom_command(
COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}" OUTPUT ${GEN_HEADER}
COMMAND "${FLATBUFFERS_FLATC_EXECUTABLE}"
${OPT} ${OPT}
-o "${SRC_FBS_DIR}" -o "${SRC_FBS_DIR}"
"${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}" "${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FBS}"
BYPRODUCTS ${GEN_HEADER} DEPENDS flatc
COMMENT "flatc generation: `${SRC_FBS}` -> `${GEN_HEADER}`" COMMENT "flatc generation: `${SRC_FBS}` -> `${GEN_HEADER}`"
) )
set(${OUT_GEN_FILE} ${GEN_HEADER} PARENT_SCOPE) set(${OUT_GEN_FILE} ${GEN_HEADER} PARENT_SCOPE)
@@ -508,25 +509,38 @@ endfunction()
function(compile_schema_for_samples SRC_FBS OPT) function(compile_schema_for_samples SRC_FBS OPT)
compile_schema("${SRC_FBS}" "${OPT}" GEN_FILE) compile_schema("${SRC_FBS}" "${OPT}" GEN_FILE)
target_sources(flatsamplebinary PRIVATE ${GEN_FILE}) target_sources(flatsample PRIVATE ${GEN_FILE})
target_sources(flatsampletext PRIVATE ${GEN_FILE})
target_sources(flatsamplebfbs PRIVATE ${GEN_FILE})
endfunction() endfunction()
if(FLATBUFFERS_BUILD_TESTS) if(FLATBUFFERS_BUILD_TESTS)
include_directories(${CMAKE_CURRENT_BINARY_DIR}/tests)
add_executable(flattests ${FlatBuffers_Tests_SRCS}) add_executable(flattests ${FlatBuffers_Tests_SRCS})
target_link_libraries(flattests PRIVATE $<BUILD_INTERFACE:ProjectConfig>) target_link_libraries(flattests PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
target_include_directories(flattests PUBLIC src) target_include_directories(flattests PUBLIC
# Ideally everything is fully qualified from the root directories
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_CURRENT_BINARY_DIR}
# TODO(derekbailey): update includes to fully qualify src/ and tests/
src
tests
${CMAKE_CURRENT_BINARY_DIR}/tests
)
# Have tests load data from the source directory, not the build directory.
add_definitions(-DFLATBUFFERS_TEST_PATH_PREFIX=${CMAKE_CURRENT_SOURCE_DIR}/)
# The flattest target needs some generated files # The flattest target needs some generated files
SET(FLATC_OPT --cpp --gen-mutable --gen-object-api --reflect-names) SET(FLATC_OPT --cpp --gen-mutable --gen-object-api --reflect-names)
SET(FLATC_OPT_COMP ${FLATC_OPT};--gen-compare) SET(FLATC_OPT_COMP ${FLATC_OPT};--gen-compare)
compile_schema_for_test(tests/alignment_test.fbs "${FLATC_OPT_COMP}") compile_schema_for_test(tests/alignment_test.fbs "${FLATC_OPT_COMP}")
compile_schema_for_test(tests/arrays_test.fbs "${FLATC_OPT_COMP};--scoped-enums")
compile_schema_for_test(tests/native_inline_table_test.fbs "${FLATC_OPT_COMP}") compile_schema_for_test(tests/native_inline_table_test.fbs "${FLATC_OPT_COMP}")
compile_schema_for_test(tests/native_type_test.fbs "${FLATC_OPT}") compile_schema_for_test(tests/native_type_test.fbs "${FLATC_OPT}")
compile_schema_for_test(tests/key_field/key_field_sample.fbs "${FLATC_OPT_COMP}") compile_schema_for_test(tests/key_field/key_field_sample.fbs "${FLATC_OPT_COMP}")
compile_schema_for_test(tests/64bit/test_64bit.fbs "${FLATC_OPT_COMP};--bfbs-gen-embed")
compile_schema_for_test(tests/64bit/evolution/v1.fbs "${FLATC_OPT_COMP}")
compile_schema_for_test(tests/64bit/evolution/v2.fbs "${FLATC_OPT_COMP}")
compile_schema_for_test(tests/union_underlying_type_test.fbs "${FLATC_OPT_COMP}")
if(FLATBUFFERS_CODE_SANITIZE) if(FLATBUFFERS_CODE_SANITIZE)
add_fsanitize_to_target(flattests ${FLATBUFFERS_CODE_SANITIZE}) add_fsanitize_to_target(flattests ${FLATBUFFERS_CODE_SANITIZE})
@@ -538,15 +552,23 @@ if(FLATBUFFERS_BUILD_TESTS)
add_executable(flatsampletext ${FlatBuffers_Sample_Text_SRCS}) add_executable(flatsampletext ${FlatBuffers_Sample_Text_SRCS})
add_executable(flatsamplebfbs ${FlatBuffers_Sample_BFBS_SRCS}) add_executable(flatsamplebfbs ${FlatBuffers_Sample_BFBS_SRCS})
target_link_libraries(flatsamplebinary PRIVATE $<BUILD_INTERFACE:ProjectConfig>) # Add a library so there is a single target that the generated samples can
target_link_libraries(flatsampletext PRIVATE $<BUILD_INTERFACE:ProjectConfig>) # link too.
target_link_libraries(flatsamplebfbs PRIVATE $<BUILD_INTERFACE:ProjectConfig>) add_library(flatsample INTERFACE)
# Since flatsample has no sources, we have to explicitly set the linker lang.
set_target_properties(flatsample PROPERTIES LINKER_LANGUAGE CXX)
compile_schema_for_samples(samples/monster.fbs "${FLATC_OPT_COMP}") compile_schema_for_samples(samples/monster.fbs "${FLATC_OPT_COMP}")
target_link_libraries(flatsamplebinary PRIVATE $<BUILD_INTERFACE:ProjectConfig> flatsample)
target_link_libraries(flatsampletext PRIVATE $<BUILD_INTERFACE:ProjectConfig> flatsample)
target_link_libraries(flatsamplebfbs PRIVATE $<BUILD_INTERFACE:ProjectConfig> flatsample)
if(FLATBUFFERS_BUILD_CPP17) if(FLATBUFFERS_BUILD_CPP17)
add_executable(flattests_cpp17 ${FlatBuffers_Tests_CPP17_SRCS}) add_executable(flattests_cpp17 ${FlatBuffers_Tests_CPP17_SRCS})
target_link_libraries(flattests_cpp17 PRIVATE $<BUILD_INTERFACE:ProjectConfig>) target_link_libraries(flattests_cpp17 PRIVATE $<BUILD_INTERFACE:ProjectConfig>)
target_include_directories(flattests_cpp17 PUBLIC src tests)
target_compile_features(flattests_cpp17 PRIVATE cxx_std_17) # requires cmake 3.8 target_compile_features(flattests_cpp17 PRIVATE cxx_std_17) # requires cmake 3.8
if(FLATBUFFERS_CODE_SANITIZE) if(FLATBUFFERS_CODE_SANITIZE)

View File

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

View File

@@ -14,6 +14,47 @@
**FlatBuffers** is a cross platform serialization library architected for **FlatBuffers** is a cross platform serialization library architected for
maximum memory efficiency. It allows you to directly access serialized data without parsing/unpacking it first, while still having great forwards/backwards compatibility. maximum memory efficiency. It allows you to directly access serialized data without parsing/unpacking it first, while still having great forwards/backwards compatibility.
## Quick Start
1. Build the compiler for flatbuffers (`flatc`)
Use `cmake` to create the build files for your platform and then perform the compliation (Linux example).
```
cmake -G "Unix Makefiles"
make -j
```
2. Define your flatbuffer schema (`.fbs`)
Write the [schema](https://flatbuffers.dev/flatbuffers_guide_writing_schema.html) to define the data you want to serialize. See [monster.fbs](https://github.com/google/flatbuffers/blob/master/samples/monster.fbs) for an example.
3. Generate code for your language(s)
Use the `flatc` compiler to take your schema and generate language-specific code:
```
./flatc --cpp --rust monster.fbs
```
Which generates `monster_generated.h` and `monster_generated.rs` files.
4. Serialize data
Use the generated code, as well as the `FlatBufferBuilder` to construct your serialized buffer. ([`C++` example](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.cpp#L24-L56))
5. Transmit/store/save Buffer
Use your serialized buffer however you want. Send it to someone, save it for later, etc...
6. Read the data
Use the generated accessors to read the data from the serialized buffer.
It doesn't need to be the same language/schema version, FlatBuffers ensures the data is readable across languages and schema versions. See the [`Rust` example](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.rs#L92-L106) reading the data written by `C++`.
## Documentation
**Go to our [landing page][] to browse our documentation.** **Go to our [landing page][] to browse our documentation.**
## Supported operating systems ## Supported operating systems
@@ -46,7 +87,7 @@ Code generation and runtime libraries for many popular languages.
## Versioning ## Versioning
FlatBuffers does not follow traditional Semver versioning (see [rationale](https://github.com/google/flatbuffers/wiki/Versioning)) but rather uses a format of the date of the release. FlatBuffers does not follow traditional SemVer versioning (see [rationale](https://github.com/google/flatbuffers/wiki/Versioning)) but rather uses a format of the date of the release.
## Contribution ## Contribution

View File

@@ -148,6 +148,7 @@ esbuild_register_toolchains(
http_file( http_file(
name = "bazel_linux_x86_64", name = "bazel_linux_x86_64",
downloaded_file_path = "bazel", downloaded_file_path = "bazel",
executable = True,
sha256 = "e89747d63443e225b140d7d37ded952dacea73aaed896bca01ccd745827c6289", sha256 = "e89747d63443e225b140d7d37ded952dacea73aaed896bca01ccd745827c6289",
urls = [ urls = [
"https://github.com/bazelbuild/bazel/releases/download/6.1.2/bazel-6.1.2-linux-x86_64", "https://github.com/bazelbuild/bazel/releases/download/6.1.2/bazel-6.1.2-linux-x86_64",

View File

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

View File

@@ -48,26 +48,9 @@ set(FlatBuffers_Library_SRCS
${FLATBUFFERS_SRC}/src/code_generators.cpp ${FLATBUFFERS_SRC}/src/code_generators.cpp
) )
set(FlatBuffers_Test_SRCS
${FLATBUFFERS_SRC}/tests/test.cpp
${FLATBUFFERS_SRC}/tests/test_assert.h
${FLATBUFFERS_SRC}/tests/test_builder.h
${FLATBUFFERS_SRC}/tests/test_assert.cpp
${FLATBUFFERS_SRC}/tests/test_builder.cpp
${FLATBUFFERS_SRC}/tests/native_type_test_impl.h
${FLATBUFFERS_SRC}/tests/native_type_test_impl.cpp
)
add_library( # Sets the name of the library. add_library( # Sets the name of the library.
flatbuffers flatbuffers
${FlatBuffers_Library_SRCS} ${FlatBuffers_Library_SRCS}
${FlatBuffers_Test_SRCS}
${Generated_SRCS} ${Generated_SRCS}
) )
add_library( # Sets the name of the library.
flatbuffers_tests
${FlatBuffers_Test_SRCS}
)

View File

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

View File

@@ -654,7 +654,7 @@ class Builder {
var tail = _tail; var tail = _tail;
_setUint32AtTail(tail, values.length); _setUint32AtTail(tail, values.length);
tail -= _sizeofUint32; tail -= _sizeofUint32;
for (var value in values) { for (final value in values) {
_setInt8AtTail(tail, value); _setInt8AtTail(tail, value);
tail -= _sizeofUint8; tail -= _sizeofUint8;
} }

View File

@@ -1,5 +1,5 @@
name: flat_buffers name: flat_buffers
version: 23.5.8 version: 23.5.26
description: FlatBuffers reading and writing library for Dart. Based on original work by Konstantin Scheglov and Paul Berry of the Dart SDK team. 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 homepage: https://github.com/google/flatbuffers
documentation: https://google.github.io/flatbuffers/index.html documentation: https://google.github.io/flatbuffers/index.html

View File

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

View File

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

View File

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

View File

@@ -23,9 +23,8 @@ GenerateGo()
GenerateJava() GenerateJava()
GenerateKotlin() GenerateKotlin()
GenerateLobster() GenerateLobster()
# TODO these doesn't respect the output prefix, fix and reenable GenerateLua()
# GenerateLua() GenerateNim()
# GenerateNim()
GeneratePhp() GeneratePhp()
GeneratePython() GeneratePython()
GenerateRust() GenerateRust()

View File

@@ -19,7 +19,7 @@ import java.nio.ByteOrder;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public final class Galaxy extends Table { public final class Galaxy extends Table {
public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_8(); } public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_26(); }
public static Galaxy getRootAsGalaxy(ByteBuffer _bb) { return getRootAsGalaxy(_bb, new Galaxy()); } public static Galaxy getRootAsGalaxy(ByteBuffer _bb) { return getRootAsGalaxy(_bb, new Galaxy()); }
public static Galaxy getRootAsGalaxy(ByteBuffer _bb, Galaxy obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } public static Galaxy getRootAsGalaxy(ByteBuffer _bb, Galaxy obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }

View File

@@ -19,7 +19,7 @@ import java.nio.ByteOrder;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public final class Universe extends Table { public final class Universe extends Table {
public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_8(); } public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_26(); }
public static Universe getRootAsUniverse(ByteBuffer _bb) { return getRootAsUniverse(_bb, new Universe()); } public static Universe getRootAsUniverse(ByteBuffer _bb) { return getRootAsUniverse(_bb, new Universe()); }
public static Universe getRootAsUniverse(ByteBuffer _bb, Universe obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } public static Universe getRootAsUniverse(ByteBuffer _bb, Universe obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }

View File

@@ -32,7 +32,7 @@ class Galaxy : Table() {
return if(o != 0) bb.getLong(o + bb_pos) else 0L return if(o != 0) bb.getLong(o + bb_pos) else 0L
} }
companion object { companion object {
fun validateVersion() = Constants.FLATBUFFERS_23_5_8() fun validateVersion() = Constants.FLATBUFFERS_23_5_26()
fun getRootAsGalaxy(_bb: ByteBuffer): Galaxy = getRootAsGalaxy(_bb, Galaxy()) fun getRootAsGalaxy(_bb: ByteBuffer): Galaxy = getRootAsGalaxy(_bb, Galaxy())
fun getRootAsGalaxy(_bb: ByteBuffer, obj: Galaxy): Galaxy { fun getRootAsGalaxy(_bb: ByteBuffer, obj: Galaxy): Galaxy {
_bb.order(ByteOrder.LITTLE_ENDIAN) _bb.order(ByteOrder.LITTLE_ENDIAN)

View File

@@ -45,7 +45,7 @@ class Universe : Table() {
val o = __offset(6); return if (o != 0) __vector_len(o) else 0 val o = __offset(6); return if (o != 0) __vector_len(o) else 0
} }
companion object { companion object {
fun validateVersion() = Constants.FLATBUFFERS_23_5_8() fun validateVersion() = Constants.FLATBUFFERS_23_5_26()
fun getRootAsUniverse(_bb: ByteBuffer): Universe = getRootAsUniverse(_bb, Universe()) fun getRootAsUniverse(_bb: ByteBuffer): Universe = getRootAsUniverse(_bb, Universe())
fun getRootAsUniverse(_bb: ByteBuffer, obj: Universe): Universe { fun getRootAsUniverse(_bb: ByteBuffer, obj: Universe): Universe {
_bb.order(ByteOrder.LITTLE_ENDIAN) _bb.order(ByteOrder.LITTLE_ENDIAN)

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

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

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

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

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

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

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

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

View File

@@ -6,7 +6,7 @@ import FlatBuffers
public struct Galaxy: FlatBufferObject, Verifiable { public struct Galaxy: FlatBufferObject, Verifiable {
static func validateVersion() { FlatBuffersVersion_23_5_8() } static func validateVersion() { FlatBuffersVersion_23_5_26() }
public var __buffer: ByteBuffer! { return _accessor.bb } public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table private var _accessor: Table
@@ -41,7 +41,7 @@ public struct Galaxy: FlatBufferObject, Verifiable {
public struct Universe: FlatBufferObject, Verifiable { public struct Universe: FlatBufferObject, Verifiable {
static func validateVersion() { FlatBuffersVersion_23_5_8() } static func validateVersion() { FlatBuffersVersion_23_5_26() }
public var __buffer: ByteBuffer! { return _accessor.bb } public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table private var _accessor: Table

View File

@@ -40,7 +40,7 @@ def Start(builder):
def HelloReplyAddMessage(builder, message): def HelloReplyAddMessage(builder, message):
builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(message), 0) builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(message), 0)
def AddMessage(builder: flatbuffers.Builder, message: int): def AddMessage(builder, message):
HelloReplyAddMessage(builder, message) HelloReplyAddMessage(builder, message)
def HelloReplyEnd(builder): def HelloReplyEnd(builder):

View File

@@ -40,7 +40,7 @@ def Start(builder):
def HelloRequestAddName(builder, name): def HelloRequestAddName(builder, name):
builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0) builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0)
def AddName(builder: flatbuffers.Builder, name: int): def AddName(builder, name):
HelloRequestAddName(builder, name) HelloRequestAddName(builder, name)
def HelloRequestEnd(builder): def HelloRequestEnd(builder):

View File

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

View File

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

View File

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

View File

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

View File

@@ -23,6 +23,10 @@
namespace flatbuffers { namespace flatbuffers {
struct CodeGenOptions {
std::string output_path;
};
// A code generator interface for producing converting flatbuffer schema into // A code generator interface for producing converting flatbuffer schema into
// code. // code.
class CodeGenerator { class CodeGenerator {
@@ -44,9 +48,20 @@ class CodeGenerator {
virtual Status GenerateCode(const Parser &parser, const std::string &path, virtual Status GenerateCode(const Parser &parser, const std::string &path,
const std::string &filename) = 0; const std::string &filename) = 0;
// Generate code from the provided `parser` and place it in the output.
virtual Status GenerateCodeString(const Parser &parser,
const std::string &filename,
std::string &output) {
(void)parser;
(void)filename;
(void)output;
return Status::NOT_IMPLEMENTED;
}
// Generate code from the provided `buffer` of given `length`. The buffer is a // Generate code from the provided `buffer` of given `length`. The buffer is a
// serialized reflection.fbs. // serialized reflection.fbs.
virtual Status GenerateCode(const uint8_t *buffer, int64_t length) = 0; virtual Status GenerateCode(const uint8_t *buffer, int64_t length,
const CodeGenOptions &options) = 0;
virtual Status GenerateMakeRule(const Parser &parser, const std::string &path, virtual Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename, const std::string &filename,

View File

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

View File

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

View File

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

View File

@@ -20,7 +20,6 @@
// Helper functionality to glue FlatBuffers and GRPC. // Helper functionality to glue FlatBuffers and GRPC.
#include "flatbuffers/flatbuffers.h" #include "flatbuffers/flatbuffers.h"
#include "grpc/byte_buffer_reader.h"
#include "grpcpp/support/byte_buffer.h" #include "grpcpp/support/byte_buffer.h"
#include "grpcpp/support/slice.h" #include "grpcpp/support/slice.h"

View File

@@ -45,26 +45,27 @@ namespace flatbuffers {
// of type tokens. // of type tokens.
// clang-format off // clang-format off
#define FLATBUFFERS_GEN_TYPES_SCALAR(TD) \ #define FLATBUFFERS_GEN_TYPES_SCALAR(TD) \
TD(NONE, "", uint8_t, byte, byte, byte, uint8, u8, UByte, UInt8, 0) \ TD(NONE, "", uint8_t, byte, byte, byte, uint8, u8, UByte, UInt8, 0) \
TD(UTYPE, "", uint8_t, byte, byte, byte, uint8, u8, UByte, UInt8, 1) /* begin scalar/int */ \ TD(UTYPE, "", uint8_t, byte, byte, byte, uint8, u8, UByte, UInt8, 1) /* begin scalar/int */ \
TD(BOOL, "bool", uint8_t, boolean,bool, bool, bool, bool, Boolean, Bool, 2) \ TD(BOOL, "bool", uint8_t, boolean,bool, bool, bool, bool, Boolean, Bool, 2) \
TD(CHAR, "byte", int8_t, byte, int8, sbyte, int8, i8, Byte, Int8, 3) \ TD(CHAR, "byte", int8_t, byte, int8, sbyte, int8, i8, Byte, Int8, 3) \
TD(UCHAR, "ubyte", uint8_t, byte, byte, byte, uint8, u8, UByte, UInt8, 4) \ TD(UCHAR, "ubyte", uint8_t, byte, byte, byte, uint8, u8, UByte, UInt8, 4) \
TD(SHORT, "short", int16_t, short, int16, short, int16, i16, Short, Int16, 5) \ TD(SHORT, "short", int16_t, short, int16, short, int16, i16, Short, Int16, 5) \
TD(USHORT, "ushort", uint16_t, short, uint16, ushort, uint16, u16, UShort, UInt16, 6) \ TD(USHORT, "ushort", uint16_t, short, uint16, ushort, uint16, u16, UShort, UInt16, 6) \
TD(INT, "int", int32_t, int, int32, int, int32, i32, Int, Int32, 7) \ TD(INT, "int", int32_t, int, int32, int, int32, i32, Int, Int32, 7) \
TD(UINT, "uint", uint32_t, int, uint32, uint, uint32, u32, UInt, UInt32, 8) \ TD(UINT, "uint", uint32_t, int, uint32, uint, uint32, u32, UInt, UInt32, 8) \
TD(LONG, "long", int64_t, long, int64, long, int64, i64, Long, Int64, 9) \ TD(LONG, "long", int64_t, long, int64, long, int64, i64, Long, Int64, 9) \
TD(ULONG, "ulong", uint64_t, long, uint64, ulong, uint64, u64, ULong, UInt64, 10) /* end int */ \ TD(ULONG, "ulong", uint64_t, long, uint64, ulong, uint64, u64, ULong, UInt64, 10) /* end int */ \
TD(FLOAT, "float", float, float, float32, float, float32, f32, Float, Float32, 11) /* begin float */ \ TD(FLOAT, "float", float, float, float32, float, float32, f32, Float, Float32, 11) /* begin float */ \
TD(DOUBLE, "double", double, double, float64, double, float64, f64, Double, Double, 12) /* end float/scalar */ TD(DOUBLE, "double", double, double, float64, double, float64, f64, Double, Double, 12) /* end float/scalar */
#define FLATBUFFERS_GEN_TYPES_POINTER(TD) \ #define FLATBUFFERS_GEN_TYPES_POINTER(TD) \
TD(STRING, "string", Offset<void>, int, int, StringOffset, int, unused, Int, Offset<String>, 13) \ TD(STRING, "string", Offset<void>, int, int, StringOffset, int, unused, Int, Offset<String>, 13) \
TD(VECTOR, "", Offset<void>, int, int, VectorOffset, int, unused, Int, Offset<UOffset>, 14) \ TD(VECTOR, "", Offset<void>, int, int, VectorOffset, int, unused, Int, Offset<UOffset>, 14) \
TD(STRUCT, "", Offset<void>, int, int, int, int, unused, Int, Offset<UOffset>, 15) \ TD(VECTOR64, "", Offset64<void>, int, int, VectorOffset, int, unused, Int, Offset<UOffset>, 18) \
TD(UNION, "", Offset<void>, int, int, int, int, unused, Int, Offset<UOffset>, 16) TD(STRUCT, "", Offset<void>, int, int, int, int, unused, Int, Offset<UOffset>, 15) \
TD(UNION, "", Offset<void>, int, int, int, int, unused, Int, Offset<UOffset>, 16)
#define FLATBUFFERS_GEN_TYPE_ARRAY(TD) \ #define FLATBUFFERS_GEN_TYPE_ARRAY(TD) \
TD(ARRAY, "", int, int, int, int, int, unused, Int, Offset<UOffset>, 17) TD(ARRAY, "", int, int, int, int, int, unused, Int, Offset<UOffset>, 17)
// The fields are: // The fields are:
// - enum // - enum
// - FlatBuffers schema type. // - FlatBuffers schema type.
@@ -139,6 +140,8 @@ inline bool IsLong (BaseType t) { return t == BASE_TYPE_LONG ||
inline bool IsBool (BaseType t) { return t == BASE_TYPE_BOOL; } inline bool IsBool (BaseType t) { return t == BASE_TYPE_BOOL; }
inline bool IsOneByte(BaseType t) { return t >= BASE_TYPE_UTYPE && inline bool IsOneByte(BaseType t) { return t >= BASE_TYPE_UTYPE &&
t <= BASE_TYPE_UCHAR; } t <= BASE_TYPE_UCHAR; }
inline bool IsVector (BaseType t) { return t == BASE_TYPE_VECTOR ||
t == BASE_TYPE_VECTOR64; }
inline bool IsUnsigned(BaseType t) { inline bool IsUnsigned(BaseType t) {
return (t == BASE_TYPE_UTYPE) || (t == BASE_TYPE_UCHAR) || return (t == BASE_TYPE_UTYPE) || (t == BASE_TYPE_UCHAR) ||
@@ -210,7 +213,8 @@ struct Type {
bool Deserialize(const Parser &parser, const reflection::Type *type); bool Deserialize(const Parser &parser, const reflection::Type *type);
BaseType base_type; BaseType base_type;
BaseType element; // only set if t == BASE_TYPE_VECTOR BaseType element; // only set if t == BASE_TYPE_VECTOR or
// BASE_TYPE_VECTOR64
StructDef *struct_def; // only set if t or element == BASE_TYPE_STRUCT StructDef *struct_def; // only set if t or element == BASE_TYPE_STRUCT
EnumDef *enum_def; // set if t == BASE_TYPE_UNION / BASE_TYPE_UTYPE, EnumDef *enum_def; // set if t == BASE_TYPE_UNION / BASE_TYPE_UTYPE,
// or for an integral type derived from an enum. // or for an integral type derived from an enum.
@@ -326,6 +330,7 @@ struct FieldDef : public Definition {
shared(false), shared(false),
native_inline(false), native_inline(false),
flexbuffer(false), flexbuffer(false),
offset64(false),
presence(kDefault), presence(kDefault),
nested_flatbuffer(nullptr), nested_flatbuffer(nullptr),
padding(0), padding(0),
@@ -352,6 +357,7 @@ struct FieldDef : public Definition {
bool native_inline; // Field will be defined inline (instead of as a pointer) bool native_inline; // Field will be defined inline (instead of as a pointer)
// for native tables if field is a struct. // for native tables if field is a struct.
bool flexbuffer; // This field contains FlexBuffer data. bool flexbuffer; // This field contains FlexBuffer data.
bool offset64; // If the field uses 64-bit offsets.
enum Presence { enum Presence {
// Field must always be present. // Field must always be present.
@@ -528,9 +534,7 @@ inline bool IsUnionType(const Type &type) {
return IsUnion(type) && IsInteger(type.base_type); return IsUnion(type) && IsInteger(type.base_type);
} }
inline bool IsVector(const Type &type) { inline bool IsVector(const Type &type) { return IsVector(type.base_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()); return IsVector(type) && IsStruct(type.VectorType());
@@ -952,6 +956,13 @@ class Parser : public ParserState {
known_attributes_["native_default"] = true; known_attributes_["native_default"] = true;
known_attributes_["flexbuffer"] = true; known_attributes_["flexbuffer"] = true;
known_attributes_["private"] = true; known_attributes_["private"] = true;
// An attribute added to a field to indicate that is uses 64-bit addressing.
known_attributes_["offset64"] = true;
// An attribute added to a vector field to indicate that it uses 64-bit
// addressing and it has a 64-bit length.
known_attributes_["vector64"] = true;
} }
// Copying is not allowed // Copying is not allowed
@@ -1062,7 +1073,7 @@ class Parser : public ParserState {
FLATBUFFERS_CHECKED_ERROR ParseAnyValue(Value &val, FieldDef *field, FLATBUFFERS_CHECKED_ERROR ParseAnyValue(Value &val, FieldDef *field,
size_t parent_fieldn, size_t parent_fieldn,
const StructDef *parent_struct_def, const StructDef *parent_struct_def,
uoffset_t count, size_t count,
bool inside_vector = false); bool inside_vector = false);
template<typename F> template<typename F>
FLATBUFFERS_CHECKED_ERROR ParseTableDelimiters(size_t &fieldn, FLATBUFFERS_CHECKED_ERROR ParseTableDelimiters(size_t &fieldn,
@@ -1074,7 +1085,7 @@ class Parser : public ParserState {
void SerializeStruct(FlatBufferBuilder &builder, const StructDef &struct_def, void SerializeStruct(FlatBufferBuilder &builder, const StructDef &struct_def,
const Value &val); const Value &val);
template<typename F> template<typename F>
FLATBUFFERS_CHECKED_ERROR ParseVectorDelimiters(uoffset_t &count, F body); FLATBUFFERS_CHECKED_ERROR ParseVectorDelimiters(size_t &count, F body);
FLATBUFFERS_CHECKED_ERROR ParseVector(const Type &type, uoffset_t *ovalue, FLATBUFFERS_CHECKED_ERROR ParseVector(const Type &type, uoffset_t *ovalue,
FieldDef *field, size_t fieldn); FieldDef *field, size_t fieldn);
FLATBUFFERS_CHECKED_ERROR ParseArray(Value &array); FLATBUFFERS_CHECKED_ERROR ParseArray(Value &array);
@@ -1139,6 +1150,8 @@ class Parser : public ParserState {
bool SupportsAdvancedArrayFeatures() const; bool SupportsAdvancedArrayFeatures() const;
bool SupportsOptionalScalars() const; bool SupportsOptionalScalars() const;
bool SupportsDefaultVectorsAndStrings() const; bool SupportsDefaultVectorsAndStrings() const;
bool Supports64BitOffsets() const;
bool SupportsUnionUnderlyingType() const;
Namespace *UniqueNamespace(Namespace *ns); Namespace *UniqueNamespace(Namespace *ns);
FLATBUFFERS_CHECKED_ERROR RecurseError(); FLATBUFFERS_CHECKED_ERROR RecurseError();
@@ -1198,138 +1211,17 @@ class Parser : public ParserState {
// if it is less than 0, no linefeeds will be generated either. // if it is less than 0, no linefeeds will be generated either.
// See idl_gen_text.cpp. // See idl_gen_text.cpp.
// strict_json adds "quotes" around field names if true. // strict_json adds "quotes" around field names if true.
// If the flatbuffer cannot be encoded in JSON (e.g., it contains non-UTF-8 // These functions return nullptr on success, or an error string,
// byte arrays in String values), returns false. // which may happen if the flatbuffer cannot be encoded in JSON (e.g.,
extern const char *GenerateTextFromTable(const Parser &parser, const void *table, // it contains non-UTF-8 byte arrays in String values).
const std::string &tablename, extern const char *GenTextFromTable(const Parser &parser, const void *table,
std::string *text); const std::string &tablename,
extern const char *GenerateText(const Parser &parser, const void *flatbuffer, std::string *text);
std::string *text); extern const char *GenText(const Parser &parser, const void *flatbuffer,
extern const char *GenerateTextFile(const Parser &parser, std::string *text);
const std::string &path, extern const char *GenTextFile(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate Json schema to string
// See idl_gen_json_schema.cpp.
extern bool GenerateJsonSchema(const Parser &parser, std::string *json);
// Generate binary files from a given FlatBuffer, and a given Parser
// object that has been populated with the corresponding schema.
// See code_generators.cpp.
extern bool GenerateBinary(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate a C++ header from the definitions in the Parser object.
// See idl_gen_cpp.
extern bool GenerateCPP(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate C# files from the definitions in the Parser object.
// See idl_gen_csharp.cpp.
extern bool GenerateCSharp(const Parser &parser, const std::string &path,
const std::string &file_name);
extern bool GenerateDart(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate Java files from the definitions in the Parser object.
// See idl_gen_java.cpp.
extern bool GenerateJava(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate JavaScript or TypeScript code from the definitions in the Parser
// object. See idl_gen_js.
extern bool GenerateTS(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate Go files from the definitions in the Parser object.
// See idl_gen_go.cpp.
extern bool GenerateGo(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate Php code from the definitions in the Parser object.
// See idl_gen_php.
extern bool GeneratePhp(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate Python files from the definitions in the Parser object.
// See idl_gen_python.cpp.
extern bool GeneratePython(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate Lobster files from the definitions in the Parser object.
// See idl_gen_lobster.cpp.
extern bool GenerateLobster(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate Lua files from the definitions in the Parser object.
// See idl_gen_lua.cpp.
extern bool GenerateLua(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate Rust files from the definitions in the Parser object.
// See idl_gen_rust.cpp.
extern bool GenerateRust(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate Json schema file
// See idl_gen_json_schema.cpp.
extern bool GenerateJsonSchema(const Parser &parser, const std::string &path,
const std::string &file_name); const std::string &file_name);
extern bool GenerateKotlin(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate Swift classes.
// See idl_gen_swift.cpp
extern bool GenerateSwift(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate a schema file from the internal representation, useful after
// parsing a .proto schema.
extern std::string GenerateFBS(const Parser &parser,
const std::string &file_name,
bool no_log);
extern bool GenerateFBS(const Parser &parser, const std::string &path,
const std::string &file_name, bool no_log);
// Generate a make rule for the generated TypeScript code.
// See idl_gen_ts.cpp.
extern std::string TSMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate a make rule for the generated C++ header.
// See idl_gen_cpp.cpp.
extern std::string CPPMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate a make rule for the generated Dart code
// see idl_gen_dart.cpp
extern std::string DartMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate a make rule for the generated Rust code.
// See idl_gen_rust.cpp.
extern std::string RustMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate a make rule for generated Java or C# files.
// See code_generators.cpp.
extern std::string CSharpMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name);
extern std::string JavaMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate a make rule for the generated text (JSON) files.
// See idl_gen_text.cpp.
extern std::string TextMakeRule(const Parser &parser, const std::string &path,
const std::string &file_names);
// Generate a make rule for the generated binary files.
// See code_generators.cpp.
extern std::string BinaryMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate GRPC Cpp interfaces. // Generate GRPC Cpp interfaces.
// See idl_gen_grpc.cpp. // See idl_gen_grpc.cpp.
bool GenerateCppGRPC(const Parser &parser, const std::string &path, bool GenerateCppGRPC(const Parser &parser, const std::string &path,
@@ -1357,9 +1249,6 @@ extern bool GenerateSwiftGRPC(const Parser &parser, const std::string &path,
extern bool GenerateTSGRPC(const Parser &parser, const std::string &path, extern bool GenerateTSGRPC(const Parser &parser, const std::string &path,
const std::string &file_name); const std::string &file_name);
extern bool GenerateRustModuleRootFile(const Parser &parser,
const std::string &path);
} // namespace flatbuffers } // namespace flatbuffers
#endif // FLATBUFFERS_IDL_H_ #endif // FLATBUFFERS_IDL_H_

View File

@@ -66,6 +66,7 @@ inline size_t GetTypeSize(reflection::BaseType base_type) {
4, // Union 4, // Union
0, // Array. Only used in structs. 0 was chosen to prevent out-of-bounds 0, // Array. Only used in structs. 0 was chosen to prevent out-of-bounds
// errors. // errors.
8, // Vector64
0 // MaxBaseType. This must be kept the last entry in this array. 0 // MaxBaseType. This must be kept the last entry in this array.
}; };

View File

@@ -10,7 +10,7 @@
// generated, otherwise it may not be compatible. // generated, otherwise it may not be compatible.
static_assert(FLATBUFFERS_VERSION_MAJOR == 23 && static_assert(FLATBUFFERS_VERSION_MAJOR == 23 &&
FLATBUFFERS_VERSION_MINOR == 5 && FLATBUFFERS_VERSION_MINOR == 5 &&
FLATBUFFERS_VERSION_REVISION == 8, FLATBUFFERS_VERSION_REVISION == 26,
"Non-compatible flatbuffers version included"); "Non-compatible flatbuffers version included");
namespace reflection { namespace reflection {
@@ -64,10 +64,11 @@ enum BaseType {
Obj = 15, Obj = 15,
Union = 16, Union = 16,
Array = 17, Array = 17,
MaxBaseType = 18 Vector64 = 18,
MaxBaseType = 19
}; };
inline const BaseType (&EnumValuesBaseType())[19] { inline const BaseType (&EnumValuesBaseType())[20] {
static const BaseType values[] = { static const BaseType values[] = {
None, None,
UType, UType,
@@ -87,13 +88,14 @@ inline const BaseType (&EnumValuesBaseType())[19] {
Obj, Obj,
Union, Union,
Array, Array,
Vector64,
MaxBaseType MaxBaseType
}; };
return values; return values;
} }
inline const char * const *EnumNamesBaseType() { inline const char * const *EnumNamesBaseType() {
static const char * const names[20] = { static const char * const names[21] = {
"None", "None",
"UType", "UType",
"Bool", "Bool",
@@ -112,6 +114,7 @@ inline const char * const *EnumNamesBaseType() {
"Obj", "Obj",
"Union", "Union",
"Array", "Array",
"Vector64",
"MaxBaseType", "MaxBaseType",
nullptr nullptr
}; };
@@ -601,7 +604,8 @@ struct Field FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table {
VT_ATTRIBUTES = 22, VT_ATTRIBUTES = 22,
VT_DOCUMENTATION = 24, VT_DOCUMENTATION = 24,
VT_OPTIONAL = 26, VT_OPTIONAL = 26,
VT_PADDING = 28 VT_PADDING = 28,
VT_OFFSET64 = 30
}; };
const ::flatbuffers::String *name() const { const ::flatbuffers::String *name() const {
return GetPointer<const ::flatbuffers::String *>(VT_NAME); return GetPointer<const ::flatbuffers::String *>(VT_NAME);
@@ -649,6 +653,10 @@ struct Field FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table {
uint16_t padding() const { uint16_t padding() const {
return GetField<uint16_t>(VT_PADDING, 0); return GetField<uint16_t>(VT_PADDING, 0);
} }
/// If the field uses 64-bit offsets.
bool offset64() const {
return GetField<uint8_t>(VT_OFFSET64, 0) != 0;
}
bool Verify(::flatbuffers::Verifier &verifier) const { bool Verify(::flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) && return VerifyTableStart(verifier) &&
VerifyOffsetRequired(verifier, VT_NAME) && VerifyOffsetRequired(verifier, VT_NAME) &&
@@ -670,6 +678,7 @@ struct Field FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table {
verifier.VerifyVectorOfStrings(documentation()) && verifier.VerifyVectorOfStrings(documentation()) &&
VerifyField<uint8_t>(verifier, VT_OPTIONAL, 1) && VerifyField<uint8_t>(verifier, VT_OPTIONAL, 1) &&
VerifyField<uint16_t>(verifier, VT_PADDING, 2) && VerifyField<uint16_t>(verifier, VT_PADDING, 2) &&
VerifyField<uint8_t>(verifier, VT_OFFSET64, 1) &&
verifier.EndTable(); verifier.EndTable();
} }
}; };
@@ -717,6 +726,9 @@ struct FieldBuilder {
void add_padding(uint16_t padding) { void add_padding(uint16_t padding) {
fbb_.AddElement<uint16_t>(Field::VT_PADDING, padding, 0); fbb_.AddElement<uint16_t>(Field::VT_PADDING, padding, 0);
} }
void add_offset64(bool offset64) {
fbb_.AddElement<uint8_t>(Field::VT_OFFSET64, static_cast<uint8_t>(offset64), 0);
}
explicit FieldBuilder(::flatbuffers::FlatBufferBuilder &_fbb) explicit FieldBuilder(::flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) { : fbb_(_fbb) {
start_ = fbb_.StartTable(); start_ = fbb_.StartTable();
@@ -744,7 +756,8 @@ inline ::flatbuffers::Offset<Field> CreateField(
::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<reflection::KeyValue>>> attributes = 0, ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<reflection::KeyValue>>> attributes = 0,
::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> documentation = 0, ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> documentation = 0,
bool optional = false, bool optional = false,
uint16_t padding = 0) { uint16_t padding = 0,
bool offset64 = false) {
FieldBuilder builder_(_fbb); FieldBuilder builder_(_fbb);
builder_.add_default_real(default_real); builder_.add_default_real(default_real);
builder_.add_default_integer(default_integer); builder_.add_default_integer(default_integer);
@@ -755,6 +768,7 @@ inline ::flatbuffers::Offset<Field> CreateField(
builder_.add_padding(padding); builder_.add_padding(padding);
builder_.add_offset(offset); builder_.add_offset(offset);
builder_.add_id(id); builder_.add_id(id);
builder_.add_offset64(offset64);
builder_.add_optional(optional); builder_.add_optional(optional);
builder_.add_key(key); builder_.add_key(key);
builder_.add_required(required); builder_.add_required(required);
@@ -776,7 +790,8 @@ inline ::flatbuffers::Offset<Field> CreateFieldDirect(
std::vector<::flatbuffers::Offset<reflection::KeyValue>> *attributes = nullptr, std::vector<::flatbuffers::Offset<reflection::KeyValue>> *attributes = nullptr,
const std::vector<::flatbuffers::Offset<::flatbuffers::String>> *documentation = nullptr, const std::vector<::flatbuffers::Offset<::flatbuffers::String>> *documentation = nullptr,
bool optional = false, bool optional = false,
uint16_t padding = 0) { uint16_t padding = 0,
bool offset64 = false) {
auto name__ = name ? _fbb.CreateString(name) : 0; auto name__ = name ? _fbb.CreateString(name) : 0;
auto attributes__ = attributes ? _fbb.CreateVectorOfSortedTables<reflection::KeyValue>(attributes) : 0; auto attributes__ = attributes ? _fbb.CreateVectorOfSortedTables<reflection::KeyValue>(attributes) : 0;
auto documentation__ = documentation ? _fbb.CreateVector<::flatbuffers::Offset<::flatbuffers::String>>(*documentation) : 0; auto documentation__ = documentation ? _fbb.CreateVector<::flatbuffers::Offset<::flatbuffers::String>>(*documentation) : 0;
@@ -794,7 +809,8 @@ inline ::flatbuffers::Offset<Field> CreateFieldDirect(
attributes__, attributes__,
documentation__, documentation__,
optional, optional,
padding); padding,
offset64);
} }
struct Object FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { struct Object FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table {

View File

@@ -52,10 +52,10 @@ class Registry {
Parser parser; Parser parser;
if (!LoadSchema(ident, &parser)) return false; if (!LoadSchema(ident, &parser)) return false;
// Now we're ready to generate text. // Now we're ready to generate text.
auto err = GenerateText(parser, flatbuf, dest); auto err = GenText(parser, flatbuf, dest);
if (err) { if (err) {
lasterror_ = "unable to generate text for FlatBuffer binary: " + lasterror_ =
std::string(err); "unable to generate text for FlatBuffer binary: " + std::string(err);
return false; return false;
} }
return true; return true;

View File

@@ -47,14 +47,24 @@ class Table {
return field_offset ? ReadScalar<T>(data_ + field_offset) : defaultval; return field_offset ? ReadScalar<T>(data_ + field_offset) : defaultval;
} }
template<typename P> P GetPointer(voffset_t field) { template<typename P, typename OffsetSize = uoffset_t>
P GetPointer(voffset_t field) {
auto field_offset = GetOptionalFieldOffset(field); auto field_offset = GetOptionalFieldOffset(field);
auto p = data_ + field_offset; auto p = data_ + field_offset;
return field_offset ? reinterpret_cast<P>(p + ReadScalar<uoffset_t>(p)) return field_offset ? reinterpret_cast<P>(p + ReadScalar<OffsetSize>(p))
: nullptr; : nullptr;
} }
template<typename P> P GetPointer(voffset_t field) const { template<typename P, typename OffsetSize = uoffset_t>
return const_cast<Table *>(this)->GetPointer<P>(field); P GetPointer(voffset_t field) const {
return const_cast<Table *>(this)->GetPointer<P, OffsetSize>(field);
}
template<typename P> P GetPointer64(voffset_t field) {
return GetPointer<P, uoffset64_t>(field);
}
template<typename P> P GetPointer64(voffset_t field) const {
return GetPointer<P, uoffset64_t>(field);
} }
template<typename P> P GetStruct(voffset_t field) const { template<typename P> P GetStruct(voffset_t field) const {
@@ -131,15 +141,25 @@ class Table {
} }
// Versions for offsets. // Versions for offsets.
template<typename OffsetT = uoffset_t>
bool VerifyOffset(const Verifier &verifier, voffset_t field) const { bool VerifyOffset(const Verifier &verifier, voffset_t field) const {
auto field_offset = GetOptionalFieldOffset(field); auto field_offset = GetOptionalFieldOffset(field);
return !field_offset || verifier.VerifyOffset(data_, field_offset); return !field_offset || verifier.VerifyOffset<OffsetT>(data_, field_offset);
} }
template<typename OffsetT = uoffset_t>
bool VerifyOffsetRequired(const Verifier &verifier, voffset_t field) const { bool VerifyOffsetRequired(const Verifier &verifier, voffset_t field) const {
auto field_offset = GetOptionalFieldOffset(field); auto field_offset = GetOptionalFieldOffset(field);
return verifier.Check(field_offset != 0) && return verifier.Check(field_offset != 0) &&
verifier.VerifyOffset(data_, field_offset); verifier.VerifyOffset<OffsetT>(data_, field_offset);
}
bool VerifyOffset64(const Verifier &verifier, voffset_t field) const {
return VerifyOffset<uoffset64_t>(verifier, field);
}
bool VerifyOffset64Required(const Verifier &verifier, voffset_t field) const {
return VerifyOffsetRequired<uoffset64_t>(verifier, field);
} }
private: private:

View File

@@ -257,7 +257,7 @@ inline void strtoval_impl(double *val, const char *str, char **endptr) {
} }
// UBSAN: double to float is safe if numeric_limits<float>::is_iec559 is true. // UBSAN: double to float is safe if numeric_limits<float>::is_iec559 is true.
__suppress_ubsan__("float-cast-overflow") FLATBUFFERS_SUPPRESS_UBSAN("float-cast-overflow")
inline void strtoval_impl(float *val, const char *str, char **endptr) { inline void strtoval_impl(float *val, const char *str, char **endptr) {
*val = __strtof_impl(str, endptr); *val = __strtof_impl(str, endptr);
} }
@@ -623,7 +623,7 @@ inline bool EscapeString(const char *s, size_t length, std::string *_text,
// we previously checked for non-UTF-8, so we shouldn't reach // we previously checked for non-UTF-8, so we shouldn't reach
// here. // here.
// //
// 2) We reached here by someone calling GenerateText() // 2) We reached here by someone calling GenText()
// on a previously-serialized flatbuffer. The data might have // on a previously-serialized flatbuffer. The data might have
// non-UTF-8 Strings, or might be corrupt. // non-UTF-8 Strings, or might be corrupt.
// //

View File

@@ -27,7 +27,8 @@ struct String;
// An STL compatible iterator implementation for Vector below, effectively // An STL compatible iterator implementation for Vector below, effectively
// calling Get() for every element. // calling Get() for every element.
template<typename T, typename IT, typename Data = uint8_t *> template<typename T, typename IT, typename Data = uint8_t *,
typename SizeT = uoffset_t>
struct VectorIterator { struct VectorIterator {
typedef std::random_access_iterator_tag iterator_category; typedef std::random_access_iterator_tag iterator_category;
typedef IT value_type; typedef IT value_type;
@@ -35,8 +36,9 @@ struct VectorIterator {
typedef IT *pointer; typedef IT *pointer;
typedef IT &reference; typedef IT &reference;
VectorIterator(Data data, uoffset_t i) static const SizeT element_stride = IndirectHelper<T>::element_stride;
: data_(data + IndirectHelper<T>::element_stride * i) {}
VectorIterator(Data data, SizeT i) : data_(data + element_stride * i) {}
VectorIterator(const VectorIterator &other) : data_(other.data_) {} VectorIterator(const VectorIterator &other) : data_(other.data_) {}
VectorIterator() : data_(nullptr) {} VectorIterator() : data_(nullptr) {}
@@ -63,7 +65,7 @@ struct VectorIterator {
} }
difference_type operator-(const VectorIterator &other) const { difference_type operator-(const VectorIterator &other) const {
return (data_ - other.data_) / IndirectHelper<T>::element_stride; return (data_ - other.data_) / element_stride;
} }
// Note: return type is incompatible with the standard // Note: return type is incompatible with the standard
@@ -75,44 +77,42 @@ struct VectorIterator {
IT operator->() const { return IndirectHelper<T>::Read(data_, 0); } IT operator->() const { return IndirectHelper<T>::Read(data_, 0); }
VectorIterator &operator++() { VectorIterator &operator++() {
data_ += IndirectHelper<T>::element_stride; data_ += element_stride;
return *this; return *this;
} }
VectorIterator operator++(int) { VectorIterator operator++(int) {
VectorIterator temp(data_, 0); VectorIterator temp(data_, 0);
data_ += IndirectHelper<T>::element_stride; data_ += element_stride;
return temp; return temp;
} }
VectorIterator operator+(const uoffset_t &offset) const { VectorIterator operator+(const SizeT &offset) const {
return VectorIterator(data_ + offset * IndirectHelper<T>::element_stride, return VectorIterator(data_ + offset * element_stride, 0);
0);
} }
VectorIterator &operator+=(const uoffset_t &offset) { VectorIterator &operator+=(const SizeT &offset) {
data_ += offset * IndirectHelper<T>::element_stride; data_ += offset * element_stride;
return *this; return *this;
} }
VectorIterator &operator--() { VectorIterator &operator--() {
data_ -= IndirectHelper<T>::element_stride; data_ -= element_stride;
return *this; return *this;
} }
VectorIterator operator--(int) { VectorIterator operator--(int) {
VectorIterator temp(data_, 0); VectorIterator temp(data_, 0);
data_ -= IndirectHelper<T>::element_stride; data_ -= element_stride;
return temp; return temp;
} }
VectorIterator operator-(const uoffset_t &offset) const { VectorIterator operator-(const SizeT &offset) const {
return VectorIterator(data_ - offset * IndirectHelper<T>::element_stride, return VectorIterator(data_ - offset * element_stride, 0);
0);
} }
VectorIterator &operator-=(const uoffset_t &offset) { VectorIterator &operator-=(const SizeT &offset) {
data_ -= offset * IndirectHelper<T>::element_stride; data_ -= offset * element_stride;
return *this; return *this;
} }
@@ -120,8 +120,8 @@ struct VectorIterator {
Data data_; Data data_;
}; };
template<typename T, typename IT> template<typename T, typename IT, typename SizeT = uoffset_t>
using VectorConstIterator = VectorIterator<T, IT, const uint8_t *>; using VectorConstIterator = VectorIterator<T, IT, const uint8_t *, SizeT>;
template<typename Iterator> template<typename Iterator>
struct VectorReverseIterator : public std::reverse_iterator<Iterator> { struct VectorReverseIterator : public std::reverse_iterator<Iterator> {
@@ -145,11 +145,12 @@ struct VectorReverseIterator : public std::reverse_iterator<Iterator> {
// This is used as a helper type for accessing vectors. // This is used as a helper type for accessing vectors.
// Vector::data() assumes the vector elements start after the length field. // Vector::data() assumes the vector elements start after the length field.
template<typename T> class Vector { template<typename T, typename SizeT = uoffset_t> class Vector {
public: public:
typedef VectorIterator<T, typename IndirectHelper<T>::mutable_return_type> typedef VectorIterator<T, typename IndirectHelper<T>::mutable_return_type,
uint8_t *, SizeT>
iterator; iterator;
typedef VectorConstIterator<T, typename IndirectHelper<T>::return_type> typedef VectorConstIterator<T, typename IndirectHelper<T>::return_type, SizeT>
const_iterator; const_iterator;
typedef VectorReverseIterator<iterator> reverse_iterator; typedef VectorReverseIterator<iterator> reverse_iterator;
typedef VectorReverseIterator<const_iterator> const_reverse_iterator; typedef VectorReverseIterator<const_iterator> const_reverse_iterator;
@@ -160,39 +161,40 @@ template<typename T> class Vector {
static FLATBUFFERS_CONSTEXPR bool is_span_observable = static FLATBUFFERS_CONSTEXPR bool is_span_observable =
scalar_tag::value && (FLATBUFFERS_LITTLEENDIAN || sizeof(T) == 1); scalar_tag::value && (FLATBUFFERS_LITTLEENDIAN || sizeof(T) == 1);
uoffset_t size() const { return EndianScalar(length_); } SizeT size() const { return EndianScalar(length_); }
// Deprecated: use size(). Here for backwards compatibility. // Deprecated: use size(). Here for backwards compatibility.
FLATBUFFERS_ATTRIBUTE([[deprecated("use size() instead")]]) FLATBUFFERS_ATTRIBUTE([[deprecated("use size() instead")]])
uoffset_t Length() const { return size(); } SizeT Length() const { return size(); }
typedef SizeT size_type;
typedef typename IndirectHelper<T>::return_type return_type; typedef typename IndirectHelper<T>::return_type return_type;
typedef typename IndirectHelper<T>::mutable_return_type mutable_return_type; typedef typename IndirectHelper<T>::mutable_return_type mutable_return_type;
typedef return_type value_type; typedef return_type value_type;
return_type Get(uoffset_t i) const { return_type Get(SizeT i) const {
FLATBUFFERS_ASSERT(i < size()); FLATBUFFERS_ASSERT(i < size());
return IndirectHelper<T>::Read(Data(), i); return IndirectHelper<T>::Read(Data(), i);
} }
return_type operator[](uoffset_t i) const { return Get(i); } return_type operator[](SizeT i) const { return Get(i); }
// If this is a Vector of enums, T will be its storage type, not the enum // If this is a Vector of enums, T will be its storage type, not the enum
// type. This function makes it convenient to retrieve value with enum // type. This function makes it convenient to retrieve value with enum
// type E. // type E.
template<typename E> E GetEnum(uoffset_t i) const { template<typename E> E GetEnum(SizeT i) const {
return static_cast<E>(Get(i)); return static_cast<E>(Get(i));
} }
// If this a vector of unions, this does the cast for you. There's no check // If this a vector of unions, this does the cast for you. There's no check
// to make sure this is the right type! // to make sure this is the right type!
template<typename U> const U *GetAs(uoffset_t i) const { template<typename U> const U *GetAs(SizeT i) const {
return reinterpret_cast<const U *>(Get(i)); return reinterpret_cast<const U *>(Get(i));
} }
// If this a vector of unions, this does the cast for you. There's no check // If this a vector of unions, this does the cast for you. There's no check
// to make sure this is actually a string! // to make sure this is actually a string!
const String *GetAsString(uoffset_t i) const { const String *GetAsString(SizeT i) const {
return reinterpret_cast<const String *>(Get(i)); return reinterpret_cast<const String *>(Get(i));
} }
@@ -226,7 +228,7 @@ template<typename T> class Vector {
// Change elements if you have a non-const pointer to this object. // Change elements if you have a non-const pointer to this object.
// Scalars only. See reflection.h, and the documentation. // Scalars only. See reflection.h, and the documentation.
void Mutate(uoffset_t i, const T &val) { void Mutate(SizeT i, const T &val) {
FLATBUFFERS_ASSERT(i < size()); FLATBUFFERS_ASSERT(i < size());
WriteScalar(data() + i, val); WriteScalar(data() + i, val);
} }
@@ -234,15 +236,15 @@ template<typename T> class Vector {
// Change an element of a vector of tables (or strings). // Change an element of a vector of tables (or strings).
// "val" points to the new table/string, as you can obtain from // "val" points to the new table/string, as you can obtain from
// e.g. reflection::AddFlatBuffer(). // e.g. reflection::AddFlatBuffer().
void MutateOffset(uoffset_t i, const uint8_t *val) { void MutateOffset(SizeT i, const uint8_t *val) {
FLATBUFFERS_ASSERT(i < size()); FLATBUFFERS_ASSERT(i < size());
static_assert(sizeof(T) == sizeof(uoffset_t), "Unrelated types"); static_assert(sizeof(T) == sizeof(SizeT), "Unrelated types");
WriteScalar(data() + i, WriteScalar(data() + i,
static_cast<uoffset_t>(val - (Data() + i * sizeof(uoffset_t)))); static_cast<SizeT>(val - (Data() + i * sizeof(SizeT))));
} }
// Get a mutable pointer to tables/strings inside this vector. // Get a mutable pointer to tables/strings inside this vector.
mutable_return_type GetMutableObject(uoffset_t i) const { mutable_return_type GetMutableObject(SizeT i) const {
FLATBUFFERS_ASSERT(i < size()); FLATBUFFERS_ASSERT(i < size());
return const_cast<mutable_return_type>(IndirectHelper<T>::Read(Data(), i)); return const_cast<mutable_return_type>(IndirectHelper<T>::Read(Data(), i));
} }
@@ -280,7 +282,7 @@ template<typename T> class Vector {
// try to construct these manually. // try to construct these manually.
Vector(); Vector();
uoffset_t length_; SizeT length_;
private: private:
// This class is a pointer. Copying will therefore create an invalid object. // This class is a pointer. Copying will therefore create an invalid object.
@@ -299,6 +301,8 @@ template<typename T> class Vector {
} }
}; };
template<typename T> using Vector64 = Vector<T, uoffset64_t>;
template<class U> template<class U>
FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span<U> make_span(Vector<U> &vec) FLATBUFFERS_CONSTEXPR_CPP11 flatbuffers::span<U> make_span(Vector<U> &vec)
FLATBUFFERS_NOEXCEPT { FLATBUFFERS_NOEXCEPT {

View File

@@ -18,6 +18,7 @@
#define FLATBUFFERS_VECTOR_DOWNWARD_H_ #define FLATBUFFERS_VECTOR_DOWNWARD_H_
#include <algorithm> #include <algorithm>
#include <cstdint>
#include "flatbuffers/base.h" #include "flatbuffers/base.h"
#include "flatbuffers/default_allocator.h" #include "flatbuffers/default_allocator.h"
@@ -31,13 +32,15 @@ namespace flatbuffers {
// Since this vector leaves the lower part unused, we support a "scratch-pad" // Since this vector leaves the lower part unused, we support a "scratch-pad"
// that can be stored there for temporary data, to share the allocated space. // that can be stored there for temporary data, to share the allocated space.
// Essentially, this supports 2 std::vectors in a single buffer. // Essentially, this supports 2 std::vectors in a single buffer.
class vector_downward { template<typename SizeT = uoffset_t> class vector_downward {
public: public:
explicit vector_downward(size_t initial_size, Allocator *allocator, explicit vector_downward(size_t initial_size, Allocator *allocator,
bool own_allocator, size_t buffer_minalign) bool own_allocator, size_t buffer_minalign,
const SizeT max_size = FLATBUFFERS_MAX_BUFFER_SIZE)
: allocator_(allocator), : allocator_(allocator),
own_allocator_(own_allocator), own_allocator_(own_allocator),
initial_size_(initial_size), initial_size_(initial_size),
max_size_(max_size),
buffer_minalign_(buffer_minalign), buffer_minalign_(buffer_minalign),
reserved_(0), reserved_(0),
size_(0), size_(0),
@@ -50,6 +53,7 @@ class vector_downward {
: allocator_(other.allocator_), : allocator_(other.allocator_),
own_allocator_(other.own_allocator_), own_allocator_(other.own_allocator_),
initial_size_(other.initial_size_), initial_size_(other.initial_size_),
max_size_(other.max_size_),
buffer_minalign_(other.buffer_minalign_), buffer_minalign_(other.buffer_minalign_),
reserved_(other.reserved_), reserved_(other.reserved_),
size_(other.size_), size_(other.size_),
@@ -111,7 +115,7 @@ class vector_downward {
uint8_t *release_raw(size_t &allocated_bytes, size_t &offset) { uint8_t *release_raw(size_t &allocated_bytes, size_t &offset) {
auto *buf = buf_; auto *buf = buf_;
allocated_bytes = reserved_; allocated_bytes = reserved_;
offset = static_cast<size_t>(cur_ - buf_); offset = vector_downward::offset();
// release_raw only relinquishes the buffer ownership. // release_raw only relinquishes the buffer ownership.
// Does not deallocate or reset the allocator. Destructor will do that. // Does not deallocate or reset the allocator. Destructor will do that.
@@ -136,10 +140,10 @@ class vector_downward {
size_t ensure_space(size_t len) { size_t ensure_space(size_t len) {
FLATBUFFERS_ASSERT(cur_ >= scratch_ && scratch_ >= buf_); FLATBUFFERS_ASSERT(cur_ >= scratch_ && scratch_ >= buf_);
if (len > static_cast<size_t>(cur_ - scratch_)) { reallocate(len); } // If the length is larger than the unused part of the buffer, we need to
// Beyond this, signed offsets may not have enough range: // grow.
// (FlatBuffers > 2GB not supported). if (len > unused_buffer_size()) { reallocate(len); }
FLATBUFFERS_ASSERT(size() < FLATBUFFERS_MAX_BUFFER_SIZE); FLATBUFFERS_ASSERT(size() < max_size_);
return len; return len;
} }
@@ -147,7 +151,7 @@ class vector_downward {
if (len) { if (len) {
ensure_space(len); ensure_space(len);
cur_ -= len; cur_ -= len;
size_ += static_cast<uoffset_t>(len); size_ += static_cast<SizeT>(len);
} }
return cur_; return cur_;
} }
@@ -155,12 +159,20 @@ class vector_downward {
// Returns nullptr if using the DefaultAllocator. // Returns nullptr if using the DefaultAllocator.
Allocator *get_custom_allocator() { return allocator_; } Allocator *get_custom_allocator() { return allocator_; }
inline uoffset_t size() const { return size_; } // The current offset into the buffer.
size_t offset() const { return cur_ - buf_; }
uoffset_t scratch_size() const { // The total size of the vector (both the buffer and scratch parts).
return static_cast<uoffset_t>(scratch_ - buf_); inline SizeT size() const { return size_; }
// The size of the buffer part of the vector that is currently unused.
SizeT unused_buffer_size() const {
return static_cast<SizeT>(cur_ - scratch_);
} }
// The size of the scratch part of the vector.
SizeT scratch_size() const { return static_cast<SizeT>(scratch_ - buf_); }
size_t capacity() const { return reserved_; } size_t capacity() const { return reserved_; }
uint8_t *data() const { uint8_t *data() const {
@@ -211,7 +223,7 @@ class vector_downward {
void pop(size_t bytes_to_remove) { void pop(size_t bytes_to_remove) {
cur_ += bytes_to_remove; cur_ += bytes_to_remove;
size_ -= static_cast<uoffset_t>(bytes_to_remove); size_ -= static_cast<SizeT>(bytes_to_remove);
} }
void scratch_pop(size_t bytes_to_remove) { scratch_ -= bytes_to_remove; } void scratch_pop(size_t bytes_to_remove) { scratch_ -= bytes_to_remove; }
@@ -224,6 +236,7 @@ class vector_downward {
swap(buffer_minalign_, other.buffer_minalign_); swap(buffer_minalign_, other.buffer_minalign_);
swap(reserved_, other.reserved_); swap(reserved_, other.reserved_);
swap(size_, other.size_); swap(size_, other.size_);
swap(max_size_, other.max_size_);
swap(buf_, other.buf_); swap(buf_, other.buf_);
swap(cur_, other.cur_); swap(cur_, other.cur_);
swap(scratch_, other.scratch_); swap(scratch_, other.scratch_);
@@ -243,9 +256,12 @@ class vector_downward {
Allocator *allocator_; Allocator *allocator_;
bool own_allocator_; bool own_allocator_;
size_t initial_size_; size_t initial_size_;
// The maximum size the vector can be.
SizeT max_size_;
size_t buffer_minalign_; size_t buffer_minalign_;
size_t reserved_; size_t reserved_;
uoffset_t size_; SizeT size_;
uint8_t *buf_; uint8_t *buf_;
uint8_t *cur_; // Points at location between empty (below) and used (above). uint8_t *cur_; // Points at location between empty (below) and used (above).
uint8_t *scratch_; // Points to the end of the scratchpad in use. uint8_t *scratch_; // Points to the end of the scratchpad in use.

View File

@@ -34,12 +34,16 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
bool check_alignment = true; bool check_alignment = true;
// If true, run verifier on nested flatbuffers // If true, run verifier on nested flatbuffers
bool check_nested_flatbuffers = true; bool check_nested_flatbuffers = true;
// The maximum size of a buffer.
size_t max_size = FLATBUFFERS_MAX_BUFFER_SIZE;
// Use assertions to check for errors.
bool assert = false;
}; };
explicit Verifier(const uint8_t *const buf, const size_t buf_len, explicit Verifier(const uint8_t *const buf, const size_t buf_len,
const Options &opts) const Options &opts)
: buf_(buf), size_(buf_len), opts_(opts) { : buf_(buf), size_(buf_len), opts_(opts) {
FLATBUFFERS_ASSERT(size_ < FLATBUFFERS_MAX_BUFFER_SIZE); FLATBUFFERS_ASSERT(size_ < opts.max_size);
} }
// Deprecated API, please construct with Verifier::Options. // Deprecated API, please construct with Verifier::Options.
@@ -58,7 +62,7 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
bool Check(const bool ok) const { bool Check(const bool ok) const {
// clang-format off // clang-format off
#ifdef FLATBUFFERS_DEBUG_VERIFICATION_FAILURE #ifdef FLATBUFFERS_DEBUG_VERIFICATION_FAILURE
FLATBUFFERS_ASSERT(ok); if (opts_.assert) { FLATBUFFERS_ASSERT(ok); }
#endif #endif
#ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
if (!ok) if (!ok)
@@ -113,41 +117,43 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
} }
// Verify a pointer (may be NULL) of any vector type. // Verify a pointer (may be NULL) of any vector type.
template<typename T> bool VerifyVector(const Vector<T> *const vec) const { template<int &..., typename T, typename LenT>
return !vec || VerifyVectorOrString(reinterpret_cast<const uint8_t *>(vec), bool VerifyVector(const Vector<T, LenT> *const vec) const {
sizeof(T)); return !vec || VerifyVectorOrString<LenT>(
reinterpret_cast<const uint8_t *>(vec), sizeof(T));
} }
// Verify a pointer (may be NULL) of a vector to struct. // Verify a pointer (may be NULL) of a vector to struct.
template<typename T> template<int &..., typename T, typename LenT>
bool VerifyVector(const Vector<const T *> *const vec) const { bool VerifyVector(const Vector<const T *, LenT> *const vec) const {
return VerifyVector(reinterpret_cast<const Vector<T> *>(vec)); return VerifyVector(reinterpret_cast<const Vector<T, LenT> *>(vec));
} }
// Verify a pointer (may be NULL) to string. // Verify a pointer (may be NULL) to string.
bool VerifyString(const String *const str) const { bool VerifyString(const String *const str) const {
size_t end; size_t end;
return !str || (VerifyVectorOrString(reinterpret_cast<const uint8_t *>(str), return !str || (VerifyVectorOrString<uoffset_t>(
1, &end) && reinterpret_cast<const uint8_t *>(str), 1, &end) &&
Verify(end, 1) && // Must have terminator Verify(end, 1) && // Must have terminator
Check(buf_[end] == '\0')); // Terminating byte must be 0. Check(buf_[end] == '\0')); // Terminating byte must be 0.
} }
// Common code between vectors and strings. // Common code between vectors and strings.
template<typename LenT = uoffset_t>
bool VerifyVectorOrString(const uint8_t *const vec, const size_t elem_size, bool VerifyVectorOrString(const uint8_t *const vec, const size_t elem_size,
size_t *const end = nullptr) const { size_t *const end = nullptr) const {
const auto veco = static_cast<size_t>(vec - buf_); const auto vec_offset = static_cast<size_t>(vec - buf_);
// Check we can read the size field. // Check we can read the size field.
if (!Verify<uoffset_t>(veco)) return false; if (!Verify<LenT>(vec_offset)) return false;
// Check the whole array. If this is a string, the byte past the array must // Check the whole array. If this is a string, the byte past the array must
// be 0. // be 0.
const auto size = ReadScalar<uoffset_t>(vec); const LenT size = ReadScalar<LenT>(vec);
const auto max_elems = FLATBUFFERS_MAX_BUFFER_SIZE / elem_size; const auto max_elems = opts_.max_size / elem_size;
if (!Check(size < max_elems)) if (!Check(size < max_elems))
return false; // Protect against byte_size overflowing. return false; // Protect against byte_size overflowing.
const auto byte_size = sizeof(size) + elem_size * size; const auto byte_size = sizeof(LenT) + elem_size * size;
if (end) *end = veco + byte_size; if (end) *end = vec_offset + byte_size;
return Verify(veco, byte_size); return Verify(vec_offset, byte_size);
} }
// Special case for string contents, after the above has been called. // Special case for string contents, after the above has been called.
@@ -171,8 +177,8 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
return true; return true;
} }
__suppress_ubsan__("unsigned-integer-overflow") bool VerifyTableStart( FLATBUFFERS_SUPPRESS_UBSAN("unsigned-integer-overflow")
const uint8_t *const table) { bool VerifyTableStart(const uint8_t *const table) {
// Check the vtable offset. // Check the vtable offset.
const auto tableo = static_cast<size_t>(table - buf_); const auto tableo = static_cast<size_t>(table - buf_);
if (!Verify<soffset_t>(tableo)) return false; if (!Verify<soffset_t>(tableo)) return false;
@@ -203,7 +209,7 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
} }
// Call T::Verify, which must be in the generated code for this type. // Call T::Verify, which must be in the generated code for this type.
const auto o = VerifyOffset(start); const auto o = VerifyOffset<uoffset_t>(start);
return Check(o != 0) && return Check(o != 0) &&
reinterpret_cast<const T *>(buf_ + start + o)->Verify(*this) reinterpret_cast<const T *>(buf_ + start + o)->Verify(*this)
// clang-format off // clang-format off
@@ -214,8 +220,8 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
// clang-format on // clang-format on
} }
template<typename T> template<typename T, int &..., typename SizeT>
bool VerifyNestedFlatBuffer(const Vector<uint8_t> *const buf, bool VerifyNestedFlatBuffer(const Vector<uint8_t, SizeT> *const buf,
const char *const identifier) { const char *const identifier) {
// Caller opted out of this. // Caller opted out of this.
if (!opts_.check_nested_flatbuffers) return true; if (!opts_.check_nested_flatbuffers) return true;
@@ -226,7 +232,7 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
// If there is a nested buffer, it must be greater than the min size. // If there is a nested buffer, it must be greater than the min size.
if (!Check(buf->size() >= FLATBUFFERS_MIN_BUFFER_SIZE)) return false; if (!Check(buf->size() >= FLATBUFFERS_MIN_BUFFER_SIZE)) return false;
Verifier nested_verifier(buf->data(), buf->size()); Verifier nested_verifier(buf->data(), buf->size(), opts_);
return nested_verifier.VerifyBuffer<T>(identifier); return nested_verifier.VerifyBuffer<T>(identifier);
} }
@@ -237,29 +243,32 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
return VerifyBufferFromStart<T>(identifier, 0); return VerifyBufferFromStart<T>(identifier, 0);
} }
template<typename T> template<typename T, typename SizeT = uoffset_t>
bool VerifySizePrefixedBuffer(const char *const identifier) { bool VerifySizePrefixedBuffer(const char *const identifier) {
return Verify<uoffset_t>(0U) && return Verify<SizeT>(0U) &&
Check(ReadScalar<uoffset_t>(buf_) == size_ - sizeof(uoffset_t)) && // Ensure the prefixed size is within the bounds of the provided
VerifyBufferFromStart<T>(identifier, sizeof(uoffset_t)); // length.
Check(ReadScalar<SizeT>(buf_) + sizeof(SizeT) <= size_) &&
VerifyBufferFromStart<T>(identifier, sizeof(SizeT));
} }
uoffset_t VerifyOffset(const size_t start) const { template<typename OffsetT = uoffset_t, typename SOffsetT = soffset_t>
if (!Verify<uoffset_t>(start)) return 0; size_t VerifyOffset(const size_t start) const {
const auto o = ReadScalar<uoffset_t>(buf_ + start); if (!Verify<OffsetT>(start)) return 0;
const auto o = ReadScalar<OffsetT>(buf_ + start);
// May not point to itself. // May not point to itself.
if (!Check(o != 0)) return 0; if (!Check(o != 0)) return 0;
// Can't wrap around / buffers are max 2GB. // Can't wrap around larger than the max size.
if (!Check(static_cast<soffset_t>(o) >= 0)) return 0; if (!Check(static_cast<SOffsetT>(o) >= 0)) return 0;
// Must be inside the buffer to create a pointer from it (pointer outside // Must be inside the buffer to create a pointer from it (pointer outside
// buffer is UB). // buffer is UB).
if (!Verify(start + o, 1)) return 0; if (!Verify(start + o, 1)) return 0;
return o; return o;
} }
uoffset_t VerifyOffset(const uint8_t *const base, template<typename OffsetT = uoffset_t>
const voffset_t start) const { size_t VerifyOffset(const uint8_t *const base, const voffset_t start) const {
return VerifyOffset(static_cast<size_t>(base - buf_) + start); return VerifyOffset<OffsetT>(static_cast<size_t>(base - buf_) + start);
} }
// Called at the start of a table to increase counters measuring data // Called at the start of a table to increase counters measuring data
@@ -312,6 +321,12 @@ class Verifier FLATBUFFERS_FINAL_CLASS {
std::vector<uint8_t> *flex_reuse_tracker_ = nullptr; std::vector<uint8_t> *flex_reuse_tracker_ = nullptr;
}; };
// Specialization for 64-bit offsets.
template<>
inline size_t Verifier::VerifyOffset<uoffset64_t>(const size_t start) const {
return VerifyOffset<uoffset64_t, soffset64_t>(start);
}
} // namespace flatbuffers } // namespace flatbuffers
#endif // FLATBUFFERS_VERIFIER_H_ #endif // FLATBUFFERS_VERIFIER_H_

View File

@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.google.flatbuffers</groupId> <groupId>com.google.flatbuffers</groupId>
<artifactId>flatbuffers-java</artifactId> <artifactId>flatbuffers-java</artifactId>
<version>23.5.8</version> <version>23.5.26</version>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>FlatBuffers Java API</name> <name>FlatBuffers Java API</name>
<description> <description>
@@ -59,15 +59,91 @@
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<configuration> <configuration>
<release>8</release> <includes>
<testExcludes> <include>**/*Test.java</include>
<testExclude>MyGame/Example/MonsterStorageGrpc.java</testExclude> </includes>
<testExclude>MyGame/OtherNameSpace/TableBT.java</testExclude> </configuration>
</testExcludes> <version>2.22.2</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.3.0</version>
<configuration>
<additionalparam>-Xdoclint:none</additionalparam>
<additionalOptions>-Xdoclint:none</additionalOptions>
</configuration>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>5.1.2</version>
<extensions>true</extensions>
</plugin>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.8</version>
<extensions>true</extensions>
<configuration>
<serverId>ossrh</serverId>
<nexusUrl>https://oss.sonatype.org/</nexusUrl>
<autoReleaseAfterClose>true</autoReleaseAfterClose>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>3.0.1</version>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
<configuration>
<gpgArguments>
<arg>--pinentry-mode</arg>
<arg>loopback</arg>
</gpgArguments>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.5.3</version>
<configuration>
<autoVersionSubmodules>true</autoVersionSubmodules>
<useReleaseProfile>false</useReleaseProfile>
<releaseProfiles>release</releaseProfiles>
<goals>deploy</goals>
</configuration> </configuration>
<version>3.8.1</version>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
@@ -80,91 +156,39 @@
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<configuration> <configuration>
<includes> <release>8</release>
<include>**/*Test.java</include> <testExcludes>
</includes> <testExclude>MyGame/Example/MonsterStorageGrpc.java</testExclude>
<testExclude>MyGame/OtherNameSpace/TableBT.java</testExclude>
</testExcludes>
</configuration> </configuration>
<version>2.22.2</version> <version>3.8.1</version>
</plugin> </plugin>
</plugins>
</build>
</profile>
<profile>
<id>jdk8</id>
<activation>
<jdk>1.8</jdk>
</activation>
<properties>
<maven.compiler.target>8</maven.compiler.target>
<maven.compiler.source>8</maven.compiler.source>
</properties>
<build>
<plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.3.0</version>
<configuration> <configuration>
<additionalparam>-Xdoclint:none</additionalparam> <testExcludes>
<additionalOptions>-Xdoclint:none</additionalOptions> <testExclude>MyGame/Example/MonsterStorageGrpc.java</testExclude>
</configuration> <testExclude>MyGame/OtherNameSpace/TableBT.java</testExclude>
<executions> </testExcludes>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>5.1.2</version>
<extensions>true</extensions>
</plugin>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.8</version>
<extensions>true</extensions>
<configuration>
<serverId>ossrh</serverId>
<nexusUrl>https://oss.sonatype.org/</nexusUrl>
<autoReleaseAfterClose>true</autoReleaseAfterClose>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>3.0.1</version>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
<configuration>
<gpgArguments>
<arg>--pinentry-mode</arg>
<arg>loopback</arg>
</gpgArguments>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.5.3</version>
<configuration>
<autoVersionSubmodules>true</autoVersionSubmodules>
<useReleaseProfile>false</useReleaseProfile>
<releaseProfiles>release</releaseProfiles>
<goals>deploy</goals>
</configuration> </configuration>
<version>3.8.1</version>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>

View File

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

View File

@@ -23,9 +23,10 @@ public final class BaseType {
public static final byte Obj = 15; public static final byte Obj = 15;
public static final byte Union = 16; public static final byte Union = 16;
public static final byte Array = 17; public static final byte Array = 17;
public static final byte MaxBaseType = 18; public static final byte Vector64 = 18;
public static final byte MaxBaseType = 19;
public static final String[] names = { "None", "UType", "Bool", "Byte", "UByte", "Short", "UShort", "Int", "UInt", "Long", "ULong", "Float", "Double", "String", "Vector", "Obj", "Union", "Array", "MaxBaseType", }; public static final String[] names = { "None", "UType", "Bool", "Byte", "UByte", "Short", "UShort", "Int", "UInt", "Long", "ULong", "Float", "Double", "String", "Vector", "Obj", "Union", "Array", "Vector64", "MaxBaseType", };
public static String name(int e) { return names[e]; } public static String name(int e) { return names[e]; }
} }

View File

@@ -21,7 +21,7 @@ import java.nio.ByteOrder;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public final class Enum extends Table { public final class Enum extends Table {
public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_8(); } public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_26(); }
public static Enum getRootAsEnum(ByteBuffer _bb) { return getRootAsEnum(_bb, new Enum()); } public static Enum getRootAsEnum(ByteBuffer _bb) { return getRootAsEnum(_bb, new Enum()); }
public static Enum getRootAsEnum(ByteBuffer _bb, Enum obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } public static Enum getRootAsEnum(ByteBuffer _bb, Enum obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }

View File

@@ -21,7 +21,7 @@ import java.nio.ByteOrder;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public final class EnumVal extends Table { public final class EnumVal extends Table {
public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_8(); } public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_26(); }
public static EnumVal getRootAsEnumVal(ByteBuffer _bb) { return getRootAsEnumVal(_bb, new EnumVal()); } public static EnumVal getRootAsEnumVal(ByteBuffer _bb) { return getRootAsEnumVal(_bb, new EnumVal()); }
public static EnumVal getRootAsEnumVal(ByteBuffer _bb, EnumVal obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } public static EnumVal getRootAsEnumVal(ByteBuffer _bb, EnumVal obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }

View File

@@ -21,7 +21,7 @@ import java.nio.ByteOrder;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public final class Field extends Table { public final class Field extends Table {
public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_8(); } public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_26(); }
public static Field getRootAsField(ByteBuffer _bb) { return getRootAsField(_bb, new Field()); } public static Field getRootAsField(ByteBuffer _bb) { return getRootAsField(_bb, new Field()); }
public static Field getRootAsField(ByteBuffer _bb, Field obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } public static Field getRootAsField(ByteBuffer _bb, Field obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
@@ -55,6 +55,10 @@ public final class Field extends Table {
* Number of padding octets to always add after this field. Structs only. * Number of padding octets to always add after this field. Structs only.
*/ */
public int padding() { int o = __offset(28); return o != 0 ? bb.getShort(o + bb_pos) & 0xFFFF : 0; } public int padding() { int o = __offset(28); return o != 0 ? bb.getShort(o + bb_pos) & 0xFFFF : 0; }
/**
* If the field uses 64-bit offsets.
*/
public boolean offset64() { int o = __offset(30); return o != 0 ? 0!=bb.get(o + bb_pos) : false; }
public static int createField(FlatBufferBuilder builder, public static int createField(FlatBufferBuilder builder,
int nameOffset, int nameOffset,
@@ -69,8 +73,9 @@ public final class Field extends Table {
int attributesOffset, int attributesOffset,
int documentationOffset, int documentationOffset,
boolean optional, boolean optional,
int padding) { int padding,
builder.startTable(13); boolean offset64) {
builder.startTable(14);
Field.addDefaultReal(builder, defaultReal); Field.addDefaultReal(builder, defaultReal);
Field.addDefaultInteger(builder, defaultInteger); Field.addDefaultInteger(builder, defaultInteger);
Field.addDocumentation(builder, documentationOffset); Field.addDocumentation(builder, documentationOffset);
@@ -80,6 +85,7 @@ public final class Field extends Table {
Field.addPadding(builder, padding); Field.addPadding(builder, padding);
Field.addOffset(builder, offset); Field.addOffset(builder, offset);
Field.addId(builder, id); Field.addId(builder, id);
Field.addOffset64(builder, offset64);
Field.addOptional(builder, optional); Field.addOptional(builder, optional);
Field.addKey(builder, key); Field.addKey(builder, key);
Field.addRequired(builder, required); Field.addRequired(builder, required);
@@ -87,7 +93,7 @@ public final class Field extends Table {
return Field.endField(builder); return Field.endField(builder);
} }
public static void startField(FlatBufferBuilder builder) { builder.startTable(13); } public static void startField(FlatBufferBuilder builder) { builder.startTable(14); }
public static void addName(FlatBufferBuilder builder, int nameOffset) { builder.addOffset(nameOffset); builder.slot(0); } public static void addName(FlatBufferBuilder builder, int nameOffset) { builder.addOffset(nameOffset); builder.slot(0); }
public static void addType(FlatBufferBuilder builder, int typeOffset) { builder.addOffset(1, typeOffset, 0); } public static void addType(FlatBufferBuilder builder, int typeOffset) { builder.addOffset(1, typeOffset, 0); }
public static void addId(FlatBufferBuilder builder, int id) { builder.addShort(2, (short) id, (short) 0); } public static void addId(FlatBufferBuilder builder, int id) { builder.addShort(2, (short) id, (short) 0); }
@@ -105,6 +111,7 @@ public final class Field extends Table {
public static void startDocumentationVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } public static void startDocumentationVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); }
public static void addOptional(FlatBufferBuilder builder, boolean optional) { builder.addBoolean(11, optional, false); } public static void addOptional(FlatBufferBuilder builder, boolean optional) { builder.addBoolean(11, optional, false); }
public static void addPadding(FlatBufferBuilder builder, int padding) { builder.addShort(12, (short) padding, (short) 0); } public static void addPadding(FlatBufferBuilder builder, int padding) { builder.addShort(12, (short) padding, (short) 0); }
public static void addOffset64(FlatBufferBuilder builder, boolean offset64) { builder.addBoolean(13, offset64, false); }
public static int endField(FlatBufferBuilder builder) { public static int endField(FlatBufferBuilder builder) {
int o = builder.endTable(); int o = builder.endTable();
builder.required(o, 4); // name builder.required(o, 4); // name

View File

@@ -21,7 +21,7 @@ import java.nio.ByteOrder;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public final class KeyValue extends Table { public final class KeyValue extends Table {
public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_8(); } public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_26(); }
public static KeyValue getRootAsKeyValue(ByteBuffer _bb) { return getRootAsKeyValue(_bb, new KeyValue()); } public static KeyValue getRootAsKeyValue(ByteBuffer _bb) { return getRootAsKeyValue(_bb, new KeyValue()); }
public static KeyValue getRootAsKeyValue(ByteBuffer _bb, KeyValue obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } public static KeyValue getRootAsKeyValue(ByteBuffer _bb, KeyValue obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }

View File

@@ -21,7 +21,7 @@ import java.nio.ByteOrder;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public final class Object extends Table { public final class Object extends Table {
public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_8(); } public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_26(); }
public static Object getRootAsObject(ByteBuffer _bb) { return getRootAsObject(_bb, new Object()); } public static Object getRootAsObject(ByteBuffer _bb) { return getRootAsObject(_bb, new Object()); }
public static Object getRootAsObject(ByteBuffer _bb, Object obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } public static Object getRootAsObject(ByteBuffer _bb, Object obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }

View File

@@ -21,7 +21,7 @@ import java.nio.ByteOrder;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public final class RPCCall extends Table { public final class RPCCall extends Table {
public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_8(); } public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_26(); }
public static RPCCall getRootAsRPCCall(ByteBuffer _bb) { return getRootAsRPCCall(_bb, new RPCCall()); } public static RPCCall getRootAsRPCCall(ByteBuffer _bb) { return getRootAsRPCCall(_bb, new RPCCall()); }
public static RPCCall getRootAsRPCCall(ByteBuffer _bb, RPCCall obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } public static RPCCall getRootAsRPCCall(ByteBuffer _bb, RPCCall obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }

View File

@@ -21,7 +21,7 @@ import java.nio.ByteOrder;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public final class Schema extends Table { public final class Schema extends Table {
public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_8(); } public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_26(); }
public static Schema getRootAsSchema(ByteBuffer _bb) { return getRootAsSchema(_bb, new Schema()); } public static Schema getRootAsSchema(ByteBuffer _bb) { return getRootAsSchema(_bb, new Schema()); }
public static Schema getRootAsSchema(ByteBuffer _bb, Schema obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } public static Schema getRootAsSchema(ByteBuffer _bb, Schema obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public static boolean SchemaBufferHasIdentifier(ByteBuffer _bb) { return __has_identifier(_bb, "BFBS"); } public static boolean SchemaBufferHasIdentifier(ByteBuffer _bb) { return __has_identifier(_bb, "BFBS"); }

View File

@@ -26,7 +26,7 @@ import java.nio.ByteOrder;
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
public final class SchemaFile extends Table { public final class SchemaFile extends Table {
public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_8(); } public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_26(); }
public static SchemaFile getRootAsSchemaFile(ByteBuffer _bb) { return getRootAsSchemaFile(_bb, new SchemaFile()); } public static SchemaFile getRootAsSchemaFile(ByteBuffer _bb) { return getRootAsSchemaFile(_bb, new SchemaFile()); }
public static SchemaFile getRootAsSchemaFile(ByteBuffer _bb, SchemaFile obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } public static SchemaFile getRootAsSchemaFile(ByteBuffer _bb, SchemaFile obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }

View File

@@ -21,7 +21,7 @@ import java.nio.ByteOrder;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public final class Service extends Table { public final class Service extends Table {
public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_8(); } public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_26(); }
public static Service getRootAsService(ByteBuffer _bb) { return getRootAsService(_bb, new Service()); } public static Service getRootAsService(ByteBuffer _bb) { return getRootAsService(_bb, new Service()); }
public static Service getRootAsService(ByteBuffer _bb, Service obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } public static Service getRootAsService(ByteBuffer _bb, Service obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }

View File

@@ -21,7 +21,7 @@ import java.nio.ByteOrder;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public final class Type extends Table { public final class Type extends Table {
public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_8(); } public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_26(); }
public static Type getRootAsType(ByteBuffer _bb) { return getRootAsType(_bb, new Type()); } public static Type getRootAsType(ByteBuffer _bb) { return getRootAsType(_bb, new Type()); }
public static Type getRootAsType(ByteBuffer _bb, Type obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } public static Type getRootAsType(ByteBuffer _bb, Type obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }

View File

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

View File

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

View File

@@ -1,6 +1,6 @@
{ {
"name": "flatbuffers", "name": "flatbuffers",
"version": "23.5.8", "version": "23.5.26",
"description": "Memory Efficient Serialization Library", "description": "Memory Efficient Serialization Library",
"files": [ "files": [
"js/**/*.js", "js/**/*.js",
@@ -36,11 +36,11 @@
"homepage": "https://google.github.io/flatbuffers/", "homepage": "https://google.github.io/flatbuffers/",
"dependencies": {}, "dependencies": {},
"devDependencies": { "devDependencies": {
"@types/node": "18.15.11", "@types/node": "18.16.3",
"@typescript-eslint/eslint-plugin": "^5.57.0", "@typescript-eslint/eslint-plugin": "^5.59.2",
"@typescript-eslint/parser": "^5.57.0", "@typescript-eslint/parser": "^5.59.2",
"esbuild": "^0.17.14", "esbuild": "^0.17.18",
"eslint": "^8.37.0", "eslint": "^8.39.0",
"typescript": "5.0.4" "typescript": "5.0.4"
} }
} }

302
pnpm-lock.yaml generated
View File

@@ -2,28 +2,28 @@ lockfileVersion: '6.0'
devDependencies: devDependencies:
'@types/node': '@types/node':
specifier: 18.15.11 specifier: 18.16.3
version: 18.15.11 version: 18.16.3
'@typescript-eslint/eslint-plugin': '@typescript-eslint/eslint-plugin':
specifier: ^5.57.0 specifier: ^5.59.2
version: 5.57.0(@typescript-eslint/parser@5.57.0)(eslint@8.37.0)(typescript@5.0.3) version: 5.59.2(@typescript-eslint/parser@5.59.2)(eslint@8.39.0)(typescript@5.0.4)
'@typescript-eslint/parser': '@typescript-eslint/parser':
specifier: ^5.57.0 specifier: ^5.59.2
version: 5.57.0(eslint@8.37.0)(typescript@5.0.3) version: 5.59.2(eslint@8.39.0)(typescript@5.0.4)
esbuild: esbuild:
specifier: ^0.17.14 specifier: ^0.17.18
version: 0.17.14 version: 0.17.18
eslint: eslint:
specifier: ^8.37.0 specifier: ^8.39.0
version: 8.37.0 version: 8.39.0
typescript: typescript:
specifier: 5.0.3 specifier: 5.0.4
version: 5.0.3 version: 5.0.4
packages: packages:
/@esbuild/android-arm64@0.17.14: /@esbuild/android-arm64@0.17.18:
resolution: {integrity: sha512-eLOpPO1RvtsP71afiFTvS7tVFShJBCT0txiv/xjFBo5a7R7Gjw7X0IgIaFoLKhqXYAXhahoXm7qAmRXhY4guJg==} resolution: {integrity: sha512-/iq0aK0eeHgSC3z55ucMAHO05OIqmQehiGay8eP5l/5l+iEr4EIbh4/MI8xD9qRFjqzgkc0JkX0LculNC9mXBw==}
engines: {node: '>=12'} engines: {node: '>=12'}
cpu: [arm64] cpu: [arm64]
os: [android] os: [android]
@@ -31,8 +31,8 @@ packages:
dev: true dev: true
optional: true optional: true
/@esbuild/android-arm@0.17.14: /@esbuild/android-arm@0.17.18:
resolution: {integrity: sha512-0CnlwnjDU8cks0yJLXfkaU/uoLyRf9VZJs4p1PskBr2AlAHeEsFEwJEo0of/Z3g+ilw5mpyDwThlxzNEIxOE4g==} resolution: {integrity: sha512-EmwL+vUBZJ7mhFCs5lA4ZimpUH3WMAoqvOIYhVQwdIgSpHC8ImHdsRyhHAVxpDYUSm0lWvd63z0XH1IlImS2Qw==}
engines: {node: '>=12'} engines: {node: '>=12'}
cpu: [arm] cpu: [arm]
os: [android] os: [android]
@@ -40,8 +40,8 @@ packages:
dev: true dev: true
optional: true optional: true
/@esbuild/android-x64@0.17.14: /@esbuild/android-x64@0.17.18:
resolution: {integrity: sha512-nrfQYWBfLGfSGLvRVlt6xi63B5IbfHm3tZCdu/82zuFPQ7zez4XjmRtF/wIRYbJQ/DsZrxJdEvYFE67avYXyng==} resolution: {integrity: sha512-x+0efYNBF3NPW2Xc5bFOSFW7tTXdAcpfEg2nXmxegm4mJuVeS+i109m/7HMiOQ6M12aVGGFlqJX3RhNdYM2lWg==}
engines: {node: '>=12'} engines: {node: '>=12'}
cpu: [x64] cpu: [x64]
os: [android] os: [android]
@@ -49,8 +49,8 @@ packages:
dev: true dev: true
optional: true optional: true
/@esbuild/darwin-arm64@0.17.14: /@esbuild/darwin-arm64@0.17.18:
resolution: {integrity: sha512-eoSjEuDsU1ROwgBH/c+fZzuSyJUVXQTOIN9xuLs9dE/9HbV/A5IqdXHU1p2OfIMwBwOYJ9SFVGGldxeRCUJFyw==} resolution: {integrity: sha512-6tY+djEAdF48M1ONWnQb1C+6LiXrKjmqjzPNPWXhu/GzOHTHX2nh8Mo2ZAmBFg0kIodHhciEgUBtcYCAIjGbjQ==}
engines: {node: '>=12'} engines: {node: '>=12'}
cpu: [arm64] cpu: [arm64]
os: [darwin] os: [darwin]
@@ -58,8 +58,8 @@ packages:
dev: true dev: true
optional: true optional: true
/@esbuild/darwin-x64@0.17.14: /@esbuild/darwin-x64@0.17.18:
resolution: {integrity: sha512-zN0U8RWfrDttdFNkHqFYZtOH8hdi22z0pFm0aIJPsNC4QQZv7je8DWCX5iA4Zx6tRhS0CCc0XC2m7wKsbWEo5g==} resolution: {integrity: sha512-Qq84ykvLvya3dO49wVC9FFCNUfSrQJLbxhoQk/TE1r6MjHo3sFF2tlJCwMjhkBVq3/ahUisj7+EpRSz0/+8+9A==}
engines: {node: '>=12'} engines: {node: '>=12'}
cpu: [x64] cpu: [x64]
os: [darwin] os: [darwin]
@@ -67,8 +67,8 @@ packages:
dev: true dev: true
optional: true optional: true
/@esbuild/freebsd-arm64@0.17.14: /@esbuild/freebsd-arm64@0.17.18:
resolution: {integrity: sha512-z0VcD4ibeZWVQCW1O7szaLxGsx54gcCnajEJMdYoYjLiq4g1jrP2lMq6pk71dbS5+7op/L2Aod+erw+EUr28/A==} resolution: {integrity: sha512-fw/ZfxfAzuHfaQeMDhbzxp9mc+mHn1Y94VDHFHjGvt2Uxl10mT4CDavHm+/L9KG441t1QdABqkVYwakMUeyLRA==}
engines: {node: '>=12'} engines: {node: '>=12'}
cpu: [arm64] cpu: [arm64]
os: [freebsd] os: [freebsd]
@@ -76,8 +76,8 @@ packages:
dev: true dev: true
optional: true optional: true
/@esbuild/freebsd-x64@0.17.14: /@esbuild/freebsd-x64@0.17.18:
resolution: {integrity: sha512-hd9mPcxfTgJlolrPlcXkQk9BMwNBvNBsVaUe5eNUqXut6weDQH8whcNaKNF2RO8NbpT6GY8rHOK2A9y++s+ehw==} resolution: {integrity: sha512-FQFbRtTaEi8ZBi/A6kxOC0V0E9B/97vPdYjY9NdawyLd4Qk5VD5g2pbWN2VR1c0xhzcJm74HWpObPszWC+qTew==}
engines: {node: '>=12'} engines: {node: '>=12'}
cpu: [x64] cpu: [x64]
os: [freebsd] os: [freebsd]
@@ -85,8 +85,8 @@ packages:
dev: true dev: true
optional: true optional: true
/@esbuild/linux-arm64@0.17.14: /@esbuild/linux-arm64@0.17.18:
resolution: {integrity: sha512-FhAMNYOq3Iblcj9i+K0l1Fp/MHt+zBeRu/Qkf0LtrcFu3T45jcwB6A1iMsemQ42vR3GBhjNZJZTaCe3VFPbn9g==} resolution: {integrity: sha512-R7pZvQZFOY2sxUG8P6A21eq6q+eBv7JPQYIybHVf1XkQYC+lT7nDBdC7wWKTrbvMXKRaGudp/dzZCwL/863mZQ==}
engines: {node: '>=12'} engines: {node: '>=12'}
cpu: [arm64] cpu: [arm64]
os: [linux] os: [linux]
@@ -94,8 +94,8 @@ packages:
dev: true dev: true
optional: true optional: true
/@esbuild/linux-arm@0.17.14: /@esbuild/linux-arm@0.17.18:
resolution: {integrity: sha512-BNTl+wSJ1omsH8s3TkQmIIIQHwvwJrU9u1ggb9XU2KTVM4TmthRIVyxSp2qxROJHhZuW/r8fht46/QE8hU8Qvg==} resolution: {integrity: sha512-jW+UCM40LzHcouIaqv3e/oRs0JM76JfhHjCavPxMUti7VAPh8CaGSlS7cmyrdpzSk7A+8f0hiedHqr/LMnfijg==}
engines: {node: '>=12'} engines: {node: '>=12'}
cpu: [arm] cpu: [arm]
os: [linux] os: [linux]
@@ -103,8 +103,8 @@ packages:
dev: true dev: true
optional: true optional: true
/@esbuild/linux-ia32@0.17.14: /@esbuild/linux-ia32@0.17.18:
resolution: {integrity: sha512-91OK/lQ5y2v7AsmnFT+0EyxdPTNhov3y2CWMdizyMfxSxRqHazXdzgBKtlmkU2KYIc+9ZK3Vwp2KyXogEATYxQ==} resolution: {integrity: sha512-ygIMc3I7wxgXIxk6j3V00VlABIjq260i967Cp9BNAk5pOOpIXmd1RFQJQX9Io7KRsthDrQYrtcx7QCof4o3ZoQ==}
engines: {node: '>=12'} engines: {node: '>=12'}
cpu: [ia32] cpu: [ia32]
os: [linux] os: [linux]
@@ -112,8 +112,8 @@ packages:
dev: true dev: true
optional: true optional: true
/@esbuild/linux-loong64@0.17.14: /@esbuild/linux-loong64@0.17.18:
resolution: {integrity: sha512-vp15H+5NR6hubNgMluqqKza85HcGJgq7t6rMH7O3Y6ApiOWPkvW2AJfNojUQimfTp6OUrACUXfR4hmpcENXoMQ==} resolution: {integrity: sha512-bvPG+MyFs5ZlwYclCG1D744oHk1Pv7j8psF5TfYx7otCVmcJsEXgFEhQkbhNW8otDHL1a2KDINW20cfCgnzgMQ==}
engines: {node: '>=12'} engines: {node: '>=12'}
cpu: [loong64] cpu: [loong64]
os: [linux] os: [linux]
@@ -121,8 +121,8 @@ packages:
dev: true dev: true
optional: true optional: true
/@esbuild/linux-mips64el@0.17.14: /@esbuild/linux-mips64el@0.17.18:
resolution: {integrity: sha512-90TOdFV7N+fgi6c2+GO9ochEkmm9kBAKnuD5e08GQMgMINOdOFHuYLPQ91RYVrnWwQ5683sJKuLi9l4SsbJ7Hg==} resolution: {integrity: sha512-oVqckATOAGuiUOa6wr8TXaVPSa+6IwVJrGidmNZS1cZVx0HqkTMkqFGD2HIx9H1RvOwFeWYdaYbdY6B89KUMxA==}
engines: {node: '>=12'} engines: {node: '>=12'}
cpu: [mips64el] cpu: [mips64el]
os: [linux] os: [linux]
@@ -130,8 +130,8 @@ packages:
dev: true dev: true
optional: true optional: true
/@esbuild/linux-ppc64@0.17.14: /@esbuild/linux-ppc64@0.17.18:
resolution: {integrity: sha512-NnBGeoqKkTugpBOBZZoktQQ1Yqb7aHKmHxsw43NddPB2YWLAlpb7THZIzsRsTr0Xw3nqiPxbA1H31ZMOG+VVPQ==} resolution: {integrity: sha512-3dLlQO+b/LnQNxgH4l9rqa2/IwRJVN9u/bK63FhOPB4xqiRqlQAU0qDU3JJuf0BmaH0yytTBdoSBHrb2jqc5qQ==}
engines: {node: '>=12'} engines: {node: '>=12'}
cpu: [ppc64] cpu: [ppc64]
os: [linux] os: [linux]
@@ -139,8 +139,8 @@ packages:
dev: true dev: true
optional: true optional: true
/@esbuild/linux-riscv64@0.17.14: /@esbuild/linux-riscv64@0.17.18:
resolution: {integrity: sha512-0qdlKScLXA8MGVy21JUKvMzCYWovctuP8KKqhtE5A6IVPq4onxXhSuhwDd2g5sRCzNDlDjitc5sX31BzDoL5Fw==} resolution: {integrity: sha512-/x7leOyDPjZV3TcsdfrSI107zItVnsX1q2nho7hbbQoKnmoeUWjs+08rKKt4AUXju7+3aRZSsKrJtaRmsdL1xA==}
engines: {node: '>=12'} engines: {node: '>=12'}
cpu: [riscv64] cpu: [riscv64]
os: [linux] os: [linux]
@@ -148,8 +148,8 @@ packages:
dev: true dev: true
optional: true optional: true
/@esbuild/linux-s390x@0.17.14: /@esbuild/linux-s390x@0.17.18:
resolution: {integrity: sha512-Hdm2Jo1yaaOro4v3+6/zJk6ygCqIZuSDJHdHaf8nVH/tfOuoEX5Riv03Ka15LmQBYJObUTNS1UdyoMk0WUn9Ww==} resolution: {integrity: sha512-cX0I8Q9xQkL/6F5zWdYmVf5JSQt+ZfZD2bJudZrWD+4mnUvoZ3TDDXtDX2mUaq6upMFv9FlfIh4Gfun0tbGzuw==}
engines: {node: '>=12'} engines: {node: '>=12'}
cpu: [s390x] cpu: [s390x]
os: [linux] os: [linux]
@@ -157,8 +157,8 @@ packages:
dev: true dev: true
optional: true optional: true
/@esbuild/linux-x64@0.17.14: /@esbuild/linux-x64@0.17.18:
resolution: {integrity: sha512-8KHF17OstlK4DuzeF/KmSgzrTWQrkWj5boluiiq7kvJCiQVzUrmSkaBvcLB2UgHpKENO2i6BthPkmUhNDaJsVw==} resolution: {integrity: sha512-66RmRsPlYy4jFl0vG80GcNRdirx4nVWAzJmXkevgphP1qf4dsLQCpSKGM3DUQCojwU1hnepI63gNZdrr02wHUA==}
engines: {node: '>=12'} engines: {node: '>=12'}
cpu: [x64] cpu: [x64]
os: [linux] os: [linux]
@@ -166,8 +166,8 @@ packages:
dev: true dev: true
optional: true optional: true
/@esbuild/netbsd-x64@0.17.14: /@esbuild/netbsd-x64@0.17.18:
resolution: {integrity: sha512-nVwpqvb3yyXztxIT2+VsxJhB5GCgzPdk1n0HHSnchRAcxqKO6ghXwHhJnr0j/B+5FSyEqSxF4q03rbA2fKXtUQ==} resolution: {integrity: sha512-95IRY7mI2yrkLlTLb1gpDxdC5WLC5mZDi+kA9dmM5XAGxCME0F8i4bYH4jZreaJ6lIZ0B8hTrweqG1fUyW7jbg==}
engines: {node: '>=12'} engines: {node: '>=12'}
cpu: [x64] cpu: [x64]
os: [netbsd] os: [netbsd]
@@ -175,8 +175,8 @@ packages:
dev: true dev: true
optional: true optional: true
/@esbuild/openbsd-x64@0.17.14: /@esbuild/openbsd-x64@0.17.18:
resolution: {integrity: sha512-1RZ7uQQ9zcy/GSAJL1xPdN7NDdOOtNEGiJalg/MOzeakZeTrgH/DoCkbq7TaPDiPhWqnDF+4bnydxRqQD7il6g==} resolution: {integrity: sha512-WevVOgcng+8hSZ4Q3BKL3n1xTv5H6Nb53cBrtzzEjDbbnOmucEVcZeGCsCOi9bAOcDYEeBZbD2SJNBxlfP3qiA==}
engines: {node: '>=12'} engines: {node: '>=12'}
cpu: [x64] cpu: [x64]
os: [openbsd] os: [openbsd]
@@ -184,8 +184,8 @@ packages:
dev: true dev: true
optional: true optional: true
/@esbuild/sunos-x64@0.17.14: /@esbuild/sunos-x64@0.17.18:
resolution: {integrity: sha512-nqMjDsFwv7vp7msrwWRysnM38Sd44PKmW8EzV01YzDBTcTWUpczQg6mGao9VLicXSgW/iookNK6AxeogNVNDZA==} resolution: {integrity: sha512-Rzf4QfQagnwhQXVBS3BYUlxmEbcV7MY+BH5vfDZekU5eYpcffHSyjU8T0xucKVuOcdCsMo+Ur5wmgQJH2GfNrg==}
engines: {node: '>=12'} engines: {node: '>=12'}
cpu: [x64] cpu: [x64]
os: [sunos] os: [sunos]
@@ -193,8 +193,8 @@ packages:
dev: true dev: true
optional: true optional: true
/@esbuild/win32-arm64@0.17.14: /@esbuild/win32-arm64@0.17.18:
resolution: {integrity: sha512-xrD0mccTKRBBIotrITV7WVQAwNJ5+1va6L0H9zN92v2yEdjfAN7864cUaZwJS7JPEs53bDTzKFbfqVlG2HhyKQ==} resolution: {integrity: sha512-Kb3Ko/KKaWhjeAm2YoT/cNZaHaD1Yk/pa3FTsmqo9uFh1D1Rfco7BBLIPdDOozrObj2sahslFuAQGvWbgWldAg==}
engines: {node: '>=12'} engines: {node: '>=12'}
cpu: [arm64] cpu: [arm64]
os: [win32] os: [win32]
@@ -202,8 +202,8 @@ packages:
dev: true dev: true
optional: true optional: true
/@esbuild/win32-ia32@0.17.14: /@esbuild/win32-ia32@0.17.18:
resolution: {integrity: sha512-nXpkz9bbJrLLyUTYtRotSS3t5b+FOuljg8LgLdINWFs3FfqZMtbnBCZFUmBzQPyxqU87F8Av+3Nco/M3hEcu1w==} resolution: {integrity: sha512-0/xUMIdkVHwkvxfbd5+lfG7mHOf2FRrxNbPiKWg9C4fFrB8H0guClmaM3BFiRUYrznVoyxTIyC/Ou2B7QQSwmw==}
engines: {node: '>=12'} engines: {node: '>=12'}
cpu: [ia32] cpu: [ia32]
os: [win32] os: [win32]
@@ -211,8 +211,8 @@ packages:
dev: true dev: true
optional: true optional: true
/@esbuild/win32-x64@0.17.14: /@esbuild/win32-x64@0.17.18:
resolution: {integrity: sha512-gPQmsi2DKTaEgG14hc3CHXHp62k8g6qr0Pas+I4lUxRMugGSATh/Bi8Dgusoz9IQ0IfdrvLpco6kujEIBoaogA==} resolution: {integrity: sha512-qU25Ma1I3NqTSHJUOKi9sAH1/Mzuvlke0ioMJRthLXKm7JiSKVwFghlGbDLOO2sARECGhja4xYfRAZNPAkooYg==}
engines: {node: '>=12'} engines: {node: '>=12'}
cpu: [x64] cpu: [x64]
os: [win32] os: [win32]
@@ -220,18 +220,18 @@ packages:
dev: true dev: true
optional: true optional: true
/@eslint-community/eslint-utils@4.4.0(eslint@8.37.0): /@eslint-community/eslint-utils@4.4.0(eslint@8.39.0):
resolution: {integrity: sha512-1/sA4dwrzBAyeUoQ6oxahHKmrZvsnLCg4RfxW3ZFGGmQkSNQPFNLV9CUEFQP1x9EYXHTo5p6xdhZM1Ne9p/AfA==} resolution: {integrity: sha512-1/sA4dwrzBAyeUoQ6oxahHKmrZvsnLCg4RfxW3ZFGGmQkSNQPFNLV9CUEFQP1x9EYXHTo5p6xdhZM1Ne9p/AfA==}
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
peerDependencies: peerDependencies:
eslint: ^6.0.0 || ^7.0.0 || >=8.0.0 eslint: ^6.0.0 || ^7.0.0 || >=8.0.0
dependencies: dependencies:
eslint: 8.37.0 eslint: 8.39.0
eslint-visitor-keys: 3.4.0 eslint-visitor-keys: 3.4.0
dev: true dev: true
/@eslint-community/regexpp@4.5.0: /@eslint-community/regexpp@4.5.1:
resolution: {integrity: sha512-vITaYzIcNmjn5tF5uxcZ/ft7/RXGrMUIS9HalWckEOF6ESiwXKoMzAQf2UW0aVd6rnOeExTJVd5hmWXucBKGXQ==} resolution: {integrity: sha512-Z5ba73P98O1KUYCCJTUeVpja9RcGoMdncZ6T49FCUl2lN38JtCJ+3WgIDBv0AuY4WChU5PmtJmOCTlN6FZTFKQ==}
engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0} engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0}
dev: true dev: true
@@ -252,8 +252,8 @@ packages:
- supports-color - supports-color
dev: true dev: true
/@eslint/js@8.37.0: /@eslint/js@8.39.0:
resolution: {integrity: sha512-x5vzdtOOGgFVDCUs81QRB2+liax8rFg3+7hqM+QhBG0/G3F1ZsoYl97UrqgHgQ9KKT7G6c4V+aTUCgu/n22v1A==} resolution: {integrity: sha512-kf9RB0Fg7NZfap83B3QOqOGg9QmD9yBudqQXzzOtn3i4y7ZUXe5ONeW34Gwi+TxhH4mvj72R1Zc300KUMa9Bng==}
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
dev: true dev: true
@@ -302,16 +302,16 @@ packages:
resolution: {integrity: sha512-wOuvG1SN4Us4rez+tylwwwCV1psiNVOkJeM3AUWUNWg/jDQY2+HE/444y5gc+jBmRqASOm2Oeh5c1axHobwRKQ==} resolution: {integrity: sha512-wOuvG1SN4Us4rez+tylwwwCV1psiNVOkJeM3AUWUNWg/jDQY2+HE/444y5gc+jBmRqASOm2Oeh5c1axHobwRKQ==}
dev: true dev: true
/@types/node@18.15.11: /@types/node@18.16.3:
resolution: {integrity: sha512-E5Kwq2n4SbMzQOn6wnmBjuK9ouqlURrcZDVfbo9ftDDTFt3nk7ZKK4GMOzoYgnpQJKcxwQw+lGaBvvlMo0qN/Q==} resolution: {integrity: sha512-OPs5WnnT1xkCBiuQrZA4+YAV4HEJejmHneyraIaxsbev5yCEr6KMwINNFP9wQeFIw8FWcoTqF3vQsa5CDaI+8Q==}
dev: true dev: true
/@types/semver@7.3.13: /@types/semver@7.3.13:
resolution: {integrity: sha512-21cFJr9z3g5dW8B0CVI9g2O9beqaThGQ6ZFBqHfwhzLDKUxaqTIy3vnfah/UPkfOiF2pLq+tGz+W8RyCskuslw==} resolution: {integrity: sha512-21cFJr9z3g5dW8B0CVI9g2O9beqaThGQ6ZFBqHfwhzLDKUxaqTIy3vnfah/UPkfOiF2pLq+tGz+W8RyCskuslw==}
dev: true dev: true
/@typescript-eslint/eslint-plugin@5.57.0(@typescript-eslint/parser@5.57.0)(eslint@8.37.0)(typescript@5.0.3): /@typescript-eslint/eslint-plugin@5.59.2(@typescript-eslint/parser@5.59.2)(eslint@8.39.0)(typescript@5.0.4):
resolution: {integrity: sha512-itag0qpN6q2UMM6Xgk6xoHa0D0/P+M17THnr4SVgqn9Rgam5k/He33MA7/D7QoJcdMxHFyX7U9imaBonAX/6qA==} resolution: {integrity: sha512-yVrXupeHjRxLDcPKL10sGQ/QlVrA8J5IYOEWVqk0lJaSZP7X5DfnP7Ns3cc74/blmbipQ1htFNVGsHX6wsYm0A==}
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
peerDependencies: peerDependencies:
'@typescript-eslint/parser': ^5.0.0 '@typescript-eslint/parser': ^5.0.0
@@ -321,25 +321,25 @@ packages:
typescript: typescript:
optional: true optional: true
dependencies: dependencies:
'@eslint-community/regexpp': 4.5.0 '@eslint-community/regexpp': 4.5.1
'@typescript-eslint/parser': 5.57.0(eslint@8.37.0)(typescript@5.0.3) '@typescript-eslint/parser': 5.59.2(eslint@8.39.0)(typescript@5.0.4)
'@typescript-eslint/scope-manager': 5.57.0 '@typescript-eslint/scope-manager': 5.59.2
'@typescript-eslint/type-utils': 5.57.0(eslint@8.37.0)(typescript@5.0.3) '@typescript-eslint/type-utils': 5.59.2(eslint@8.39.0)(typescript@5.0.4)
'@typescript-eslint/utils': 5.57.0(eslint@8.37.0)(typescript@5.0.3) '@typescript-eslint/utils': 5.59.2(eslint@8.39.0)(typescript@5.0.4)
debug: 4.3.4 debug: 4.3.4
eslint: 8.37.0 eslint: 8.39.0
grapheme-splitter: 1.0.4 grapheme-splitter: 1.0.4
ignore: 5.2.4 ignore: 5.2.4
natural-compare-lite: 1.4.0 natural-compare-lite: 1.4.0
semver: 7.3.8 semver: 7.5.0
tsutils: 3.21.0(typescript@5.0.3) tsutils: 3.21.0(typescript@5.0.4)
typescript: 5.0.3 typescript: 5.0.4
transitivePeerDependencies: transitivePeerDependencies:
- supports-color - supports-color
dev: true dev: true
/@typescript-eslint/parser@5.57.0(eslint@8.37.0)(typescript@5.0.3): /@typescript-eslint/parser@5.59.2(eslint@8.39.0)(typescript@5.0.4):
resolution: {integrity: sha512-orrduvpWYkgLCyAdNtR1QIWovcNZlEm6yL8nwH/eTxWLd8gsP+25pdLHYzL2QdkqrieaDwLpytHqycncv0woUQ==} resolution: {integrity: sha512-uq0sKyw6ao1iFOZZGk9F8Nro/8+gfB5ezl1cA06SrqbgJAt0SRoFhb9pXaHvkrxUpZaoLxt8KlovHNk8Gp6/HQ==}
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
peerDependencies: peerDependencies:
eslint: ^6.0.0 || ^7.0.0 || ^8.0.0 eslint: ^6.0.0 || ^7.0.0 || ^8.0.0
@@ -348,26 +348,26 @@ packages:
typescript: typescript:
optional: true optional: true
dependencies: dependencies:
'@typescript-eslint/scope-manager': 5.57.0 '@typescript-eslint/scope-manager': 5.59.2
'@typescript-eslint/types': 5.57.0 '@typescript-eslint/types': 5.59.2
'@typescript-eslint/typescript-estree': 5.57.0(typescript@5.0.3) '@typescript-eslint/typescript-estree': 5.59.2(typescript@5.0.4)
debug: 4.3.4 debug: 4.3.4
eslint: 8.37.0 eslint: 8.39.0
typescript: 5.0.3 typescript: 5.0.4
transitivePeerDependencies: transitivePeerDependencies:
- supports-color - supports-color
dev: true dev: true
/@typescript-eslint/scope-manager@5.57.0: /@typescript-eslint/scope-manager@5.59.2:
resolution: {integrity: sha512-NANBNOQvllPlizl9LatX8+MHi7bx7WGIWYjPHDmQe5Si/0YEYfxSljJpoTyTWFTgRy3X8gLYSE4xQ2U+aCozSw==} resolution: {integrity: sha512-dB1v7ROySwQWKqQ8rEWcdbTsFjh2G0vn8KUyvTXdPoyzSL6lLGkiXEV5CvpJsEe9xIdKV+8Zqb7wif2issoOFA==}
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
dependencies: dependencies:
'@typescript-eslint/types': 5.57.0 '@typescript-eslint/types': 5.59.2
'@typescript-eslint/visitor-keys': 5.57.0 '@typescript-eslint/visitor-keys': 5.59.2
dev: true dev: true
/@typescript-eslint/type-utils@5.57.0(eslint@8.37.0)(typescript@5.0.3): /@typescript-eslint/type-utils@5.59.2(eslint@8.39.0)(typescript@5.0.4):
resolution: {integrity: sha512-kxXoq9zOTbvqzLbdNKy1yFrxLC6GDJFE2Yuo3KqSwTmDOFjUGeWSakgoXT864WcK5/NAJkkONCiKb1ddsqhLXQ==} resolution: {integrity: sha512-b1LS2phBOsEy/T381bxkkywfQXkV1dWda/z0PhnIy3bC5+rQWQDS7fk9CSpcXBccPY27Z6vBEuaPBCKCgYezyQ==}
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
peerDependencies: peerDependencies:
eslint: '*' eslint: '*'
@@ -376,23 +376,23 @@ packages:
typescript: typescript:
optional: true optional: true
dependencies: dependencies:
'@typescript-eslint/typescript-estree': 5.57.0(typescript@5.0.3) '@typescript-eslint/typescript-estree': 5.59.2(typescript@5.0.4)
'@typescript-eslint/utils': 5.57.0(eslint@8.37.0)(typescript@5.0.3) '@typescript-eslint/utils': 5.59.2(eslint@8.39.0)(typescript@5.0.4)
debug: 4.3.4 debug: 4.3.4
eslint: 8.37.0 eslint: 8.39.0
tsutils: 3.21.0(typescript@5.0.3) tsutils: 3.21.0(typescript@5.0.4)
typescript: 5.0.3 typescript: 5.0.4
transitivePeerDependencies: transitivePeerDependencies:
- supports-color - supports-color
dev: true dev: true
/@typescript-eslint/types@5.57.0: /@typescript-eslint/types@5.59.2:
resolution: {integrity: sha512-mxsod+aZRSyLT+jiqHw1KK6xrANm19/+VFALVFP5qa/aiJnlP38qpyaTd0fEKhWvQk6YeNZ5LGwI1pDpBRBhtQ==} resolution: {integrity: sha512-LbJ/HqoVs2XTGq5shkiKaNTuVv5tTejdHgfdjqRUGdYhjW1crm/M7og2jhVskMt8/4wS3T1+PfFvL1K3wqYj4w==}
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
dev: true dev: true
/@typescript-eslint/typescript-estree@5.57.0(typescript@5.0.3): /@typescript-eslint/typescript-estree@5.59.2(typescript@5.0.4):
resolution: {integrity: sha512-LTzQ23TV82KpO8HPnWuxM2V7ieXW8O142I7hQTxWIHDcCEIjtkat6H96PFkYBQqGFLW/G/eVVOB9Z8rcvdY/Vw==} resolution: {integrity: sha512-+j4SmbwVmZsQ9jEyBMgpuBD0rKwi9RxRpjX71Brr73RsYnEr3Lt5QZ624Bxphp8HUkSKfqGnPJp1kA5nl0Sh7Q==}
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
peerDependencies: peerDependencies:
typescript: '*' typescript: '*'
@@ -400,43 +400,43 @@ packages:
typescript: typescript:
optional: true optional: true
dependencies: dependencies:
'@typescript-eslint/types': 5.57.0 '@typescript-eslint/types': 5.59.2
'@typescript-eslint/visitor-keys': 5.57.0 '@typescript-eslint/visitor-keys': 5.59.2
debug: 4.3.4 debug: 4.3.4
globby: 11.1.0 globby: 11.1.0
is-glob: 4.0.3 is-glob: 4.0.3
semver: 7.3.8 semver: 7.5.0
tsutils: 3.21.0(typescript@5.0.3) tsutils: 3.21.0(typescript@5.0.4)
typescript: 5.0.3 typescript: 5.0.4
transitivePeerDependencies: transitivePeerDependencies:
- supports-color - supports-color
dev: true dev: true
/@typescript-eslint/utils@5.57.0(eslint@8.37.0)(typescript@5.0.3): /@typescript-eslint/utils@5.59.2(eslint@8.39.0)(typescript@5.0.4):
resolution: {integrity: sha512-ps/4WohXV7C+LTSgAL5CApxvxbMkl9B9AUZRtnEFonpIxZDIT7wC1xfvuJONMidrkB9scs4zhtRyIwHh4+18kw==} resolution: {integrity: sha512-kSuF6/77TZzyGPhGO4uVp+f0SBoYxCDf+lW3GKhtKru/L8k/Hd7NFQxyWUeY7Z/KGB2C6Fe3yf2vVi4V9TsCSQ==}
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
peerDependencies: peerDependencies:
eslint: ^6.0.0 || ^7.0.0 || ^8.0.0 eslint: ^6.0.0 || ^7.0.0 || ^8.0.0
dependencies: dependencies:
'@eslint-community/eslint-utils': 4.4.0(eslint@8.37.0) '@eslint-community/eslint-utils': 4.4.0(eslint@8.39.0)
'@types/json-schema': 7.0.11 '@types/json-schema': 7.0.11
'@types/semver': 7.3.13 '@types/semver': 7.3.13
'@typescript-eslint/scope-manager': 5.57.0 '@typescript-eslint/scope-manager': 5.59.2
'@typescript-eslint/types': 5.57.0 '@typescript-eslint/types': 5.59.2
'@typescript-eslint/typescript-estree': 5.57.0(typescript@5.0.3) '@typescript-eslint/typescript-estree': 5.59.2(typescript@5.0.4)
eslint: 8.37.0 eslint: 8.39.0
eslint-scope: 5.1.1 eslint-scope: 5.1.1
semver: 7.3.8 semver: 7.5.0
transitivePeerDependencies: transitivePeerDependencies:
- supports-color - supports-color
- typescript - typescript
dev: true dev: true
/@typescript-eslint/visitor-keys@5.57.0: /@typescript-eslint/visitor-keys@5.59.2:
resolution: {integrity: sha512-ery2g3k0hv5BLiKpPuwYt9KBkAp2ugT6VvyShXdLOkax895EC55sP0Tx5L0fZaQueiK3fBLvHVvEl3jFS5ia+g==} resolution: {integrity: sha512-EEpsO8m3RASrKAHI9jpavNv9NlEUebV4qmF1OWxSTtKSFBpC1NCmWazDQHFivRf0O1DV11BA645yrLEVQ0/Lig==}
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
dependencies: dependencies:
'@typescript-eslint/types': 5.57.0 '@typescript-eslint/types': 5.59.2
eslint-visitor-keys: 3.4.0 eslint-visitor-keys: 3.4.0
dev: true dev: true
@@ -569,34 +569,34 @@ packages:
esutils: 2.0.3 esutils: 2.0.3
dev: true dev: true
/esbuild@0.17.14: /esbuild@0.17.18:
resolution: {integrity: sha512-vOO5XhmVj/1XQR9NQ1UPq6qvMYL7QFJU57J5fKBKBKxp17uDt5PgxFDb4A2nEiXhr1qQs4x0F5+66hVVw4ruNw==} resolution: {integrity: sha512-z1lix43jBs6UKjcZVKOw2xx69ffE2aG0PygLL5qJ9OS/gy0Ewd1gW/PUQIOIQGXBHWNywSc0floSKoMFF8aK2w==}
engines: {node: '>=12'} engines: {node: '>=12'}
hasBin: true hasBin: true
requiresBuild: true requiresBuild: true
optionalDependencies: optionalDependencies:
'@esbuild/android-arm': 0.17.14 '@esbuild/android-arm': 0.17.18
'@esbuild/android-arm64': 0.17.14 '@esbuild/android-arm64': 0.17.18
'@esbuild/android-x64': 0.17.14 '@esbuild/android-x64': 0.17.18
'@esbuild/darwin-arm64': 0.17.14 '@esbuild/darwin-arm64': 0.17.18
'@esbuild/darwin-x64': 0.17.14 '@esbuild/darwin-x64': 0.17.18
'@esbuild/freebsd-arm64': 0.17.14 '@esbuild/freebsd-arm64': 0.17.18
'@esbuild/freebsd-x64': 0.17.14 '@esbuild/freebsd-x64': 0.17.18
'@esbuild/linux-arm': 0.17.14 '@esbuild/linux-arm': 0.17.18
'@esbuild/linux-arm64': 0.17.14 '@esbuild/linux-arm64': 0.17.18
'@esbuild/linux-ia32': 0.17.14 '@esbuild/linux-ia32': 0.17.18
'@esbuild/linux-loong64': 0.17.14 '@esbuild/linux-loong64': 0.17.18
'@esbuild/linux-mips64el': 0.17.14 '@esbuild/linux-mips64el': 0.17.18
'@esbuild/linux-ppc64': 0.17.14 '@esbuild/linux-ppc64': 0.17.18
'@esbuild/linux-riscv64': 0.17.14 '@esbuild/linux-riscv64': 0.17.18
'@esbuild/linux-s390x': 0.17.14 '@esbuild/linux-s390x': 0.17.18
'@esbuild/linux-x64': 0.17.14 '@esbuild/linux-x64': 0.17.18
'@esbuild/netbsd-x64': 0.17.14 '@esbuild/netbsd-x64': 0.17.18
'@esbuild/openbsd-x64': 0.17.14 '@esbuild/openbsd-x64': 0.17.18
'@esbuild/sunos-x64': 0.17.14 '@esbuild/sunos-x64': 0.17.18
'@esbuild/win32-arm64': 0.17.14 '@esbuild/win32-arm64': 0.17.18
'@esbuild/win32-ia32': 0.17.14 '@esbuild/win32-ia32': 0.17.18
'@esbuild/win32-x64': 0.17.14 '@esbuild/win32-x64': 0.17.18
dev: true dev: true
/escape-string-regexp@4.0.0: /escape-string-regexp@4.0.0:
@@ -612,8 +612,8 @@ packages:
estraverse: 4.3.0 estraverse: 4.3.0
dev: true dev: true
/eslint-scope@7.1.1: /eslint-scope@7.2.0:
resolution: {integrity: sha512-QKQM/UXpIiHcLqJ5AOyIW7XZmzjkzQXYE54n1++wb0u9V/abW3l9uQnxX8Z5Xd18xyKIMTUAyQ0k1e8pz6LUrw==} resolution: {integrity: sha512-DYj5deGlHBfMt15J7rdtyKNq/Nqlv5KfU4iodrQ019XESsRnwXH9KAE0y3cwtUHDo2ob7CypAnCqefh6vioWRw==}
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
dependencies: dependencies:
esrecurse: 4.3.0 esrecurse: 4.3.0
@@ -625,15 +625,15 @@ packages:
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
dev: true dev: true
/eslint@8.37.0: /eslint@8.39.0:
resolution: {integrity: sha512-NU3Ps9nI05GUoVMxcZx1J8CNR6xOvUT4jAUMH5+z8lpp3aEdPVCImKw6PWG4PY+Vfkpr+jvMpxs/qoE7wq0sPw==} resolution: {integrity: sha512-mwiok6cy7KTW7rBpo05k6+p4YVZByLNjAZ/ACB9DRCu4YDRwjXI01tWHp6KAUWelsBetTxKK/2sHB0vdS8Z2Og==}
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
hasBin: true hasBin: true
dependencies: dependencies:
'@eslint-community/eslint-utils': 4.4.0(eslint@8.37.0) '@eslint-community/eslint-utils': 4.4.0(eslint@8.39.0)
'@eslint-community/regexpp': 4.5.0 '@eslint-community/regexpp': 4.5.1
'@eslint/eslintrc': 2.0.2 '@eslint/eslintrc': 2.0.2
'@eslint/js': 8.37.0 '@eslint/js': 8.39.0
'@humanwhocodes/config-array': 0.11.8 '@humanwhocodes/config-array': 0.11.8
'@humanwhocodes/module-importer': 1.0.1 '@humanwhocodes/module-importer': 1.0.1
'@nodelib/fs.walk': 1.2.8 '@nodelib/fs.walk': 1.2.8
@@ -643,7 +643,7 @@ packages:
debug: 4.3.4 debug: 4.3.4
doctrine: 3.0.0 doctrine: 3.0.0
escape-string-regexp: 4.0.0 escape-string-regexp: 4.0.0
eslint-scope: 7.1.1 eslint-scope: 7.2.0
eslint-visitor-keys: 3.4.0 eslint-visitor-keys: 3.4.0
espree: 9.5.1 espree: 9.5.1
esquery: 1.5.0 esquery: 1.5.0
@@ -1064,8 +1064,8 @@ packages:
queue-microtask: 1.2.3 queue-microtask: 1.2.3
dev: true dev: true
/semver@7.3.8: /semver@7.5.0:
resolution: {integrity: sha512-NB1ctGL5rlHrPJtFDVIVzTyQylMLu9N9VICA6HSFJo8MCGVTMW6gfpicwKmmK/dAjTOrqu5l63JJOpDSrAis3A==} resolution: {integrity: sha512-+XC0AD/R7Q2mPSRuy2Id0+CGTZ98+8f+KvwirxOKIEyid+XSx6HbC63p+O4IndTHuX5Z+JxQ0TghCkO5Cg/2HA==}
engines: {node: '>=10'} engines: {node: '>=10'}
hasBin: true hasBin: true
dependencies: dependencies:
@@ -1123,14 +1123,14 @@ packages:
resolution: {integrity: sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==} resolution: {integrity: sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==}
dev: true dev: true
/tsutils@3.21.0(typescript@5.0.3): /tsutils@3.21.0(typescript@5.0.4):
resolution: {integrity: sha512-mHKK3iUXL+3UF6xL5k0PEhKRUBKPBCv/+RkEOpjRWxxx27KKRBmmA60A9pgOUvMi8GKhRMPEmjBRPzs2W7O1OA==} resolution: {integrity: sha512-mHKK3iUXL+3UF6xL5k0PEhKRUBKPBCv/+RkEOpjRWxxx27KKRBmmA60A9pgOUvMi8GKhRMPEmjBRPzs2W7O1OA==}
engines: {node: '>= 6'} engines: {node: '>= 6'}
peerDependencies: peerDependencies:
typescript: '>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta' typescript: '>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta'
dependencies: dependencies:
tslib: 1.14.1 tslib: 1.14.1
typescript: 5.0.3 typescript: 5.0.4
dev: true dev: true
/type-check@0.4.0: /type-check@0.4.0:
@@ -1145,8 +1145,8 @@ packages:
engines: {node: '>=10'} engines: {node: '>=10'}
dev: true dev: true
/typescript@5.0.3: /typescript@5.0.4:
resolution: {integrity: sha512-xv8mOEDnigb/tN9PSMTwSEqAnUvkoXMQlicOb0IUVDBSQCgBSaAAROUZYy2IcUy5qU6XajK5jjjO7TMWqBTKZA==} resolution: {integrity: sha512-cW9T5W9xY37cc+jfEnaUvX91foxtHkza3Nw3wkoF4sSlKn0MONdkdEndig/qPBWXNkmplh3NzayQzCiHM4/hqw==}
engines: {node: '>=12.20'} engines: {node: '>=12.20'}
hasBin: true hasBin: true
dev: true dev: true

View File

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

View File

@@ -21,4 +21,5 @@ class BaseType(object):
Obj = 15 Obj = 15
Union = 16 Union = 16
Array = 17 Array = 17
MaxBaseType = 18 Vector64 = 18
MaxBaseType = 19

View File

@@ -42,7 +42,7 @@ class Enum(object):
x = self._tab.Vector(o) x = self._tab.Vector(o)
x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
x = self._tab.Indirect(x) x = self._tab.Indirect(x)
from .reflection.EnumVal import EnumVal from reflection.EnumVal import EnumVal
obj = EnumVal() obj = EnumVal()
obj.Init(self._tab.Bytes, x) obj.Init(self._tab.Bytes, x)
return obj return obj
@@ -72,7 +72,7 @@ class Enum(object):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10))
if o != 0: if o != 0:
x = self._tab.Indirect(o + self._tab.Pos) x = self._tab.Indirect(o + self._tab.Pos)
from .reflection.Type import Type from reflection.Type import Type
obj = Type() obj = Type()
obj.Init(self._tab.Bytes, x) obj.Init(self._tab.Bytes, x)
return obj return obj
@@ -85,7 +85,7 @@ class Enum(object):
x = self._tab.Vector(o) x = self._tab.Vector(o)
x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
x = self._tab.Indirect(x) x = self._tab.Indirect(x)
from .reflection.KeyValue import KeyValue from reflection.KeyValue import KeyValue
obj = KeyValue() obj = KeyValue()
obj.Init(self._tab.Bytes, x) obj.Init(self._tab.Bytes, x)
return obj return obj
@@ -140,13 +140,13 @@ def Start(builder):
def EnumAddName(builder, name): def EnumAddName(builder, name):
builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0) builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0)
def AddName(builder: flatbuffers.Builder, name: int): def AddName(builder, name):
EnumAddName(builder, name) EnumAddName(builder, name)
def EnumAddValues(builder, values): def EnumAddValues(builder, values):
builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(values), 0) builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(values), 0)
def AddValues(builder: flatbuffers.Builder, values: int): def AddValues(builder, values):
EnumAddValues(builder, values) EnumAddValues(builder, values)
def EnumStartValuesVector(builder, numElems): def EnumStartValuesVector(builder, numElems):
@@ -158,19 +158,19 @@ def StartValuesVector(builder, numElems: int) -> int:
def EnumAddIsUnion(builder, isUnion): def EnumAddIsUnion(builder, isUnion):
builder.PrependBoolSlot(2, isUnion, 0) builder.PrependBoolSlot(2, isUnion, 0)
def AddIsUnion(builder: flatbuffers.Builder, isUnion: bool): def AddIsUnion(builder, isUnion):
EnumAddIsUnion(builder, isUnion) EnumAddIsUnion(builder, isUnion)
def EnumAddUnderlyingType(builder, underlyingType): def EnumAddUnderlyingType(builder, underlyingType):
builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(underlyingType), 0) builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(underlyingType), 0)
def AddUnderlyingType(builder: flatbuffers.Builder, underlyingType: int): def AddUnderlyingType(builder, underlyingType):
EnumAddUnderlyingType(builder, underlyingType) EnumAddUnderlyingType(builder, underlyingType)
def EnumAddAttributes(builder, attributes): def EnumAddAttributes(builder, attributes):
builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(attributes), 0) builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(attributes), 0)
def AddAttributes(builder: flatbuffers.Builder, attributes: int): def AddAttributes(builder, attributes):
EnumAddAttributes(builder, attributes) EnumAddAttributes(builder, attributes)
def EnumStartAttributesVector(builder, numElems): def EnumStartAttributesVector(builder, numElems):
@@ -182,7 +182,7 @@ def StartAttributesVector(builder, numElems: int) -> int:
def EnumAddDocumentation(builder, documentation): def EnumAddDocumentation(builder, documentation):
builder.PrependUOffsetTRelativeSlot(5, flatbuffers.number_types.UOffsetTFlags.py_type(documentation), 0) builder.PrependUOffsetTRelativeSlot(5, flatbuffers.number_types.UOffsetTFlags.py_type(documentation), 0)
def AddDocumentation(builder: flatbuffers.Builder, documentation: int): def AddDocumentation(builder, documentation):
EnumAddDocumentation(builder, documentation) EnumAddDocumentation(builder, documentation)
def EnumStartDocumentationVector(builder, numElems): def EnumStartDocumentationVector(builder, numElems):
@@ -194,7 +194,7 @@ def StartDocumentationVector(builder, numElems: int) -> int:
def EnumAddDeclarationFile(builder, declarationFile): def EnumAddDeclarationFile(builder, declarationFile):
builder.PrependUOffsetTRelativeSlot(6, flatbuffers.number_types.UOffsetTFlags.py_type(declarationFile), 0) builder.PrependUOffsetTRelativeSlot(6, flatbuffers.number_types.UOffsetTFlags.py_type(declarationFile), 0)
def AddDeclarationFile(builder: flatbuffers.Builder, declarationFile: int): def AddDeclarationFile(builder, declarationFile):
EnumAddDeclarationFile(builder, declarationFile) EnumAddDeclarationFile(builder, declarationFile)
def EnumEnd(builder): def EnumEnd(builder):

View File

@@ -47,7 +47,7 @@ class EnumVal(object):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10))
if o != 0: if o != 0:
x = self._tab.Indirect(o + self._tab.Pos) x = self._tab.Indirect(o + self._tab.Pos)
from .reflection.Type import Type from reflection.Type import Type
obj = Type() obj = Type()
obj.Init(self._tab.Bytes, x) obj.Init(self._tab.Bytes, x)
return obj return obj
@@ -80,7 +80,7 @@ class EnumVal(object):
x = self._tab.Vector(o) x = self._tab.Vector(o)
x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
x = self._tab.Indirect(x) x = self._tab.Indirect(x)
from .reflection.KeyValue import KeyValue from reflection.KeyValue import KeyValue
obj = KeyValue() obj = KeyValue()
obj.Init(self._tab.Bytes, x) obj.Init(self._tab.Bytes, x)
return obj return obj
@@ -107,25 +107,25 @@ def Start(builder):
def EnumValAddName(builder, name): def EnumValAddName(builder, name):
builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0) builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0)
def AddName(builder: flatbuffers.Builder, name: int): def AddName(builder, name):
EnumValAddName(builder, name) EnumValAddName(builder, name)
def EnumValAddValue(builder, value): def EnumValAddValue(builder, value):
builder.PrependInt64Slot(1, value, 0) builder.PrependInt64Slot(1, value, 0)
def AddValue(builder: flatbuffers.Builder, value: int): def AddValue(builder, value):
EnumValAddValue(builder, value) EnumValAddValue(builder, value)
def EnumValAddUnionType(builder, unionType): def EnumValAddUnionType(builder, unionType):
builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(unionType), 0) builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(unionType), 0)
def AddUnionType(builder: flatbuffers.Builder, unionType: int): def AddUnionType(builder, unionType):
EnumValAddUnionType(builder, unionType) EnumValAddUnionType(builder, unionType)
def EnumValAddDocumentation(builder, documentation): def EnumValAddDocumentation(builder, documentation):
builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(documentation), 0) builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(documentation), 0)
def AddDocumentation(builder: flatbuffers.Builder, documentation: int): def AddDocumentation(builder, documentation):
EnumValAddDocumentation(builder, documentation) EnumValAddDocumentation(builder, documentation)
def EnumValStartDocumentationVector(builder, numElems): def EnumValStartDocumentationVector(builder, numElems):
@@ -137,7 +137,7 @@ def StartDocumentationVector(builder, numElems: int) -> int:
def EnumValAddAttributes(builder, attributes): def EnumValAddAttributes(builder, attributes):
builder.PrependUOffsetTRelativeSlot(5, flatbuffers.number_types.UOffsetTFlags.py_type(attributes), 0) builder.PrependUOffsetTRelativeSlot(5, flatbuffers.number_types.UOffsetTFlags.py_type(attributes), 0)
def AddAttributes(builder: flatbuffers.Builder, attributes: int): def AddAttributes(builder, attributes):
EnumValAddAttributes(builder, attributes) EnumValAddAttributes(builder, attributes)
def EnumValStartAttributesVector(builder, numElems): def EnumValStartAttributesVector(builder, numElems):

View File

@@ -40,7 +40,7 @@ class Field(object):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
if o != 0: if o != 0:
x = self._tab.Indirect(o + self._tab.Pos) x = self._tab.Indirect(o + self._tab.Pos)
from .reflection.Type import Type from reflection.Type import Type
obj = Type() obj = Type()
obj.Init(self._tab.Bytes, x) obj.Init(self._tab.Bytes, x)
return obj return obj
@@ -102,7 +102,7 @@ class Field(object):
x = self._tab.Vector(o) x = self._tab.Vector(o)
x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
x = self._tab.Indirect(x) x = self._tab.Indirect(x)
from .reflection.KeyValue import KeyValue from reflection.KeyValue import KeyValue
obj = KeyValue() obj = KeyValue()
obj.Init(self._tab.Bytes, x) obj.Init(self._tab.Bytes, x)
return obj return obj
@@ -155,8 +155,16 @@ class Field(object):
return self._tab.Get(flatbuffers.number_types.Uint16Flags, o + self._tab.Pos) return self._tab.Get(flatbuffers.number_types.Uint16Flags, o + self._tab.Pos)
return 0 return 0
# If the field uses 64-bit offsets.
# Field
def Offset64(self):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(30))
if o != 0:
return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos))
return False
def FieldStart(builder): def FieldStart(builder):
builder.StartObject(13) builder.StartObject(14)
def Start(builder): def Start(builder):
FieldStart(builder) FieldStart(builder)
@@ -164,61 +172,61 @@ def Start(builder):
def FieldAddName(builder, name): def FieldAddName(builder, name):
builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0) builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0)
def AddName(builder: flatbuffers.Builder, name: int): def AddName(builder, name):
FieldAddName(builder, name) FieldAddName(builder, name)
def FieldAddType(builder, type): def FieldAddType(builder, type):
builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(type), 0) builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(type), 0)
def AddType(builder: flatbuffers.Builder, type: int): def AddType(builder, type):
FieldAddType(builder, type) FieldAddType(builder, type)
def FieldAddId(builder, id): def FieldAddId(builder, id):
builder.PrependUint16Slot(2, id, 0) builder.PrependUint16Slot(2, id, 0)
def AddId(builder: flatbuffers.Builder, id: int): def AddId(builder, id):
FieldAddId(builder, id) FieldAddId(builder, id)
def FieldAddOffset(builder, offset): def FieldAddOffset(builder, offset):
builder.PrependUint16Slot(3, offset, 0) builder.PrependUint16Slot(3, offset, 0)
def AddOffset(builder: flatbuffers.Builder, offset: int): def AddOffset(builder, offset):
FieldAddOffset(builder, offset) FieldAddOffset(builder, offset)
def FieldAddDefaultInteger(builder, defaultInteger): def FieldAddDefaultInteger(builder, defaultInteger):
builder.PrependInt64Slot(4, defaultInteger, 0) builder.PrependInt64Slot(4, defaultInteger, 0)
def AddDefaultInteger(builder: flatbuffers.Builder, defaultInteger: int): def AddDefaultInteger(builder, defaultInteger):
FieldAddDefaultInteger(builder, defaultInteger) FieldAddDefaultInteger(builder, defaultInteger)
def FieldAddDefaultReal(builder, defaultReal): def FieldAddDefaultReal(builder, defaultReal):
builder.PrependFloat64Slot(5, defaultReal, 0.0) builder.PrependFloat64Slot(5, defaultReal, 0.0)
def AddDefaultReal(builder: flatbuffers.Builder, defaultReal: float): def AddDefaultReal(builder, defaultReal):
FieldAddDefaultReal(builder, defaultReal) FieldAddDefaultReal(builder, defaultReal)
def FieldAddDeprecated(builder, deprecated): def FieldAddDeprecated(builder, deprecated):
builder.PrependBoolSlot(6, deprecated, 0) builder.PrependBoolSlot(6, deprecated, 0)
def AddDeprecated(builder: flatbuffers.Builder, deprecated: bool): def AddDeprecated(builder, deprecated):
FieldAddDeprecated(builder, deprecated) FieldAddDeprecated(builder, deprecated)
def FieldAddRequired(builder, required): def FieldAddRequired(builder, required):
builder.PrependBoolSlot(7, required, 0) builder.PrependBoolSlot(7, required, 0)
def AddRequired(builder: flatbuffers.Builder, required: bool): def AddRequired(builder, required):
FieldAddRequired(builder, required) FieldAddRequired(builder, required)
def FieldAddKey(builder, key): def FieldAddKey(builder, key):
builder.PrependBoolSlot(8, key, 0) builder.PrependBoolSlot(8, key, 0)
def AddKey(builder: flatbuffers.Builder, key: bool): def AddKey(builder, key):
FieldAddKey(builder, key) FieldAddKey(builder, key)
def FieldAddAttributes(builder, attributes): def FieldAddAttributes(builder, attributes):
builder.PrependUOffsetTRelativeSlot(9, flatbuffers.number_types.UOffsetTFlags.py_type(attributes), 0) builder.PrependUOffsetTRelativeSlot(9, flatbuffers.number_types.UOffsetTFlags.py_type(attributes), 0)
def AddAttributes(builder: flatbuffers.Builder, attributes: int): def AddAttributes(builder, attributes):
FieldAddAttributes(builder, attributes) FieldAddAttributes(builder, attributes)
def FieldStartAttributesVector(builder, numElems): def FieldStartAttributesVector(builder, numElems):
@@ -230,7 +238,7 @@ def StartAttributesVector(builder, numElems: int) -> int:
def FieldAddDocumentation(builder, documentation): def FieldAddDocumentation(builder, documentation):
builder.PrependUOffsetTRelativeSlot(10, flatbuffers.number_types.UOffsetTFlags.py_type(documentation), 0) builder.PrependUOffsetTRelativeSlot(10, flatbuffers.number_types.UOffsetTFlags.py_type(documentation), 0)
def AddDocumentation(builder: flatbuffers.Builder, documentation: int): def AddDocumentation(builder, documentation):
FieldAddDocumentation(builder, documentation) FieldAddDocumentation(builder, documentation)
def FieldStartDocumentationVector(builder, numElems): def FieldStartDocumentationVector(builder, numElems):
@@ -242,15 +250,21 @@ def StartDocumentationVector(builder, numElems: int) -> int:
def FieldAddOptional(builder, optional): def FieldAddOptional(builder, optional):
builder.PrependBoolSlot(11, optional, 0) builder.PrependBoolSlot(11, optional, 0)
def AddOptional(builder: flatbuffers.Builder, optional: bool): def AddOptional(builder, optional):
FieldAddOptional(builder, optional) FieldAddOptional(builder, optional)
def FieldAddPadding(builder, padding): def FieldAddPadding(builder, padding):
builder.PrependUint16Slot(12, padding, 0) builder.PrependUint16Slot(12, padding, 0)
def AddPadding(builder: flatbuffers.Builder, padding: int): def AddPadding(builder, padding):
FieldAddPadding(builder, padding) FieldAddPadding(builder, padding)
def FieldAddOffset64(builder, offset64):
builder.PrependBoolSlot(13, offset64, 0)
def AddOffset64(builder, offset64):
FieldAddOffset64(builder, offset64)
def FieldEnd(builder): def FieldEnd(builder):
return builder.EndObject() return builder.EndObject()

View File

@@ -51,13 +51,13 @@ def Start(builder):
def KeyValueAddKey(builder, key): def KeyValueAddKey(builder, key):
builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(key), 0) builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(key), 0)
def AddKey(builder: flatbuffers.Builder, key: int): def AddKey(builder, key):
KeyValueAddKey(builder, key) KeyValueAddKey(builder, key)
def KeyValueAddValue(builder, value): def KeyValueAddValue(builder, value):
builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(value), 0) builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(value), 0)
def AddValue(builder: flatbuffers.Builder, value: int): def AddValue(builder, value):
KeyValueAddValue(builder, value) KeyValueAddValue(builder, value)
def KeyValueEnd(builder): def KeyValueEnd(builder):

View File

@@ -42,7 +42,7 @@ class Object(object):
x = self._tab.Vector(o) x = self._tab.Vector(o)
x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
x = self._tab.Indirect(x) x = self._tab.Indirect(x)
from .reflection.Field import Field from reflection.Field import Field
obj = Field() obj = Field()
obj.Init(self._tab.Bytes, x) obj.Init(self._tab.Bytes, x)
return obj return obj
@@ -88,7 +88,7 @@ class Object(object):
x = self._tab.Vector(o) x = self._tab.Vector(o)
x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
x = self._tab.Indirect(x) x = self._tab.Indirect(x)
from .reflection.KeyValue import KeyValue from reflection.KeyValue import KeyValue
obj = KeyValue() obj = KeyValue()
obj.Init(self._tab.Bytes, x) obj.Init(self._tab.Bytes, x)
return obj return obj
@@ -143,13 +143,13 @@ def Start(builder):
def ObjectAddName(builder, name): def ObjectAddName(builder, name):
builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0) builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0)
def AddName(builder: flatbuffers.Builder, name: int): def AddName(builder, name):
ObjectAddName(builder, name) ObjectAddName(builder, name)
def ObjectAddFields(builder, fields): def ObjectAddFields(builder, fields):
builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(fields), 0) builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(fields), 0)
def AddFields(builder: flatbuffers.Builder, fields: int): def AddFields(builder, fields):
ObjectAddFields(builder, fields) ObjectAddFields(builder, fields)
def ObjectStartFieldsVector(builder, numElems): def ObjectStartFieldsVector(builder, numElems):
@@ -161,25 +161,25 @@ def StartFieldsVector(builder, numElems: int) -> int:
def ObjectAddIsStruct(builder, isStruct): def ObjectAddIsStruct(builder, isStruct):
builder.PrependBoolSlot(2, isStruct, 0) builder.PrependBoolSlot(2, isStruct, 0)
def AddIsStruct(builder: flatbuffers.Builder, isStruct: bool): def AddIsStruct(builder, isStruct):
ObjectAddIsStruct(builder, isStruct) ObjectAddIsStruct(builder, isStruct)
def ObjectAddMinalign(builder, minalign): def ObjectAddMinalign(builder, minalign):
builder.PrependInt32Slot(3, minalign, 0) builder.PrependInt32Slot(3, minalign, 0)
def AddMinalign(builder: flatbuffers.Builder, minalign: int): def AddMinalign(builder, minalign):
ObjectAddMinalign(builder, minalign) ObjectAddMinalign(builder, minalign)
def ObjectAddBytesize(builder, bytesize): def ObjectAddBytesize(builder, bytesize):
builder.PrependInt32Slot(4, bytesize, 0) builder.PrependInt32Slot(4, bytesize, 0)
def AddBytesize(builder: flatbuffers.Builder, bytesize: int): def AddBytesize(builder, bytesize):
ObjectAddBytesize(builder, bytesize) ObjectAddBytesize(builder, bytesize)
def ObjectAddAttributes(builder, attributes): def ObjectAddAttributes(builder, attributes):
builder.PrependUOffsetTRelativeSlot(5, flatbuffers.number_types.UOffsetTFlags.py_type(attributes), 0) builder.PrependUOffsetTRelativeSlot(5, flatbuffers.number_types.UOffsetTFlags.py_type(attributes), 0)
def AddAttributes(builder: flatbuffers.Builder, attributes: int): def AddAttributes(builder, attributes):
ObjectAddAttributes(builder, attributes) ObjectAddAttributes(builder, attributes)
def ObjectStartAttributesVector(builder, numElems): def ObjectStartAttributesVector(builder, numElems):
@@ -191,7 +191,7 @@ def StartAttributesVector(builder, numElems: int) -> int:
def ObjectAddDocumentation(builder, documentation): def ObjectAddDocumentation(builder, documentation):
builder.PrependUOffsetTRelativeSlot(6, flatbuffers.number_types.UOffsetTFlags.py_type(documentation), 0) builder.PrependUOffsetTRelativeSlot(6, flatbuffers.number_types.UOffsetTFlags.py_type(documentation), 0)
def AddDocumentation(builder: flatbuffers.Builder, documentation: int): def AddDocumentation(builder, documentation):
ObjectAddDocumentation(builder, documentation) ObjectAddDocumentation(builder, documentation)
def ObjectStartDocumentationVector(builder, numElems): def ObjectStartDocumentationVector(builder, numElems):
@@ -203,7 +203,7 @@ def StartDocumentationVector(builder, numElems: int) -> int:
def ObjectAddDeclarationFile(builder, declarationFile): def ObjectAddDeclarationFile(builder, declarationFile):
builder.PrependUOffsetTRelativeSlot(7, flatbuffers.number_types.UOffsetTFlags.py_type(declarationFile), 0) builder.PrependUOffsetTRelativeSlot(7, flatbuffers.number_types.UOffsetTFlags.py_type(declarationFile), 0)
def AddDeclarationFile(builder: flatbuffers.Builder, declarationFile: int): def AddDeclarationFile(builder, declarationFile):
ObjectAddDeclarationFile(builder, declarationFile) ObjectAddDeclarationFile(builder, declarationFile)
def ObjectEnd(builder): def ObjectEnd(builder):

View File

@@ -40,7 +40,7 @@ class RPCCall(object):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6))
if o != 0: if o != 0:
x = self._tab.Indirect(o + self._tab.Pos) x = self._tab.Indirect(o + self._tab.Pos)
from .reflection.Object import Object from reflection.Object import Object
obj = Object() obj = Object()
obj.Init(self._tab.Bytes, x) obj.Init(self._tab.Bytes, x)
return obj return obj
@@ -51,7 +51,7 @@ class RPCCall(object):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8))
if o != 0: if o != 0:
x = self._tab.Indirect(o + self._tab.Pos) x = self._tab.Indirect(o + self._tab.Pos)
from .reflection.Object import Object from reflection.Object import Object
obj = Object() obj = Object()
obj.Init(self._tab.Bytes, x) obj.Init(self._tab.Bytes, x)
return obj return obj
@@ -64,7 +64,7 @@ class RPCCall(object):
x = self._tab.Vector(o) x = self._tab.Vector(o)
x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
x = self._tab.Indirect(x) x = self._tab.Indirect(x)
from .reflection.KeyValue import KeyValue from reflection.KeyValue import KeyValue
obj = KeyValue() obj = KeyValue()
obj.Init(self._tab.Bytes, x) obj.Init(self._tab.Bytes, x)
return obj return obj
@@ -111,25 +111,25 @@ def Start(builder):
def RPCCallAddName(builder, name): def RPCCallAddName(builder, name):
builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0) builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0)
def AddName(builder: flatbuffers.Builder, name: int): def AddName(builder, name):
RPCCallAddName(builder, name) RPCCallAddName(builder, name)
def RPCCallAddRequest(builder, request): def RPCCallAddRequest(builder, request):
builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(request), 0) builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(request), 0)
def AddRequest(builder: flatbuffers.Builder, request: int): def AddRequest(builder, request):
RPCCallAddRequest(builder, request) RPCCallAddRequest(builder, request)
def RPCCallAddResponse(builder, response): def RPCCallAddResponse(builder, response):
builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(response), 0) builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(response), 0)
def AddResponse(builder: flatbuffers.Builder, response: int): def AddResponse(builder, response):
RPCCallAddResponse(builder, response) RPCCallAddResponse(builder, response)
def RPCCallAddAttributes(builder, attributes): def RPCCallAddAttributes(builder, attributes):
builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(attributes), 0) builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(attributes), 0)
def AddAttributes(builder: flatbuffers.Builder, attributes: int): def AddAttributes(builder, attributes):
RPCCallAddAttributes(builder, attributes) RPCCallAddAttributes(builder, attributes)
def RPCCallStartAttributesVector(builder, numElems): def RPCCallStartAttributesVector(builder, numElems):
@@ -141,7 +141,7 @@ def StartAttributesVector(builder, numElems: int) -> int:
def RPCCallAddDocumentation(builder, documentation): def RPCCallAddDocumentation(builder, documentation):
builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(documentation), 0) builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(documentation), 0)
def AddDocumentation(builder: flatbuffers.Builder, documentation: int): def AddDocumentation(builder, documentation):
RPCCallAddDocumentation(builder, documentation) RPCCallAddDocumentation(builder, documentation)
def RPCCallStartDocumentationVector(builder, numElems): def RPCCallStartDocumentationVector(builder, numElems):

View File

@@ -35,7 +35,7 @@ class Schema(object):
x = self._tab.Vector(o) x = self._tab.Vector(o)
x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
x = self._tab.Indirect(x) x = self._tab.Indirect(x)
from .reflection.Object import Object from reflection.Object import Object
obj = Object() obj = Object()
obj.Init(self._tab.Bytes, x) obj.Init(self._tab.Bytes, x)
return obj return obj
@@ -60,7 +60,7 @@ class Schema(object):
x = self._tab.Vector(o) x = self._tab.Vector(o)
x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
x = self._tab.Indirect(x) x = self._tab.Indirect(x)
from .reflection.Enum import Enum from reflection.Enum import Enum
obj = Enum() obj = Enum()
obj.Init(self._tab.Bytes, x) obj.Init(self._tab.Bytes, x)
return obj return obj
@@ -97,7 +97,7 @@ class Schema(object):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12))
if o != 0: if o != 0:
x = self._tab.Indirect(o + self._tab.Pos) x = self._tab.Indirect(o + self._tab.Pos)
from .reflection.Object import Object from reflection.Object import Object
obj = Object() obj = Object()
obj.Init(self._tab.Bytes, x) obj.Init(self._tab.Bytes, x)
return obj return obj
@@ -110,7 +110,7 @@ class Schema(object):
x = self._tab.Vector(o) x = self._tab.Vector(o)
x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
x = self._tab.Indirect(x) x = self._tab.Indirect(x)
from .reflection.Service import Service from reflection.Service import Service
obj = Service() obj = Service()
obj.Init(self._tab.Bytes, x) obj.Init(self._tab.Bytes, x)
return obj return obj
@@ -144,7 +144,7 @@ class Schema(object):
x = self._tab.Vector(o) x = self._tab.Vector(o)
x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
x = self._tab.Indirect(x) x = self._tab.Indirect(x)
from .reflection.SchemaFile import SchemaFile from reflection.SchemaFile import SchemaFile
obj = SchemaFile() obj = SchemaFile()
obj.Init(self._tab.Bytes, x) obj.Init(self._tab.Bytes, x)
return obj return obj
@@ -171,7 +171,7 @@ def Start(builder):
def SchemaAddObjects(builder, objects): def SchemaAddObjects(builder, objects):
builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(objects), 0) builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(objects), 0)
def AddObjects(builder: flatbuffers.Builder, objects: int): def AddObjects(builder, objects):
SchemaAddObjects(builder, objects) SchemaAddObjects(builder, objects)
def SchemaStartObjectsVector(builder, numElems): def SchemaStartObjectsVector(builder, numElems):
@@ -183,7 +183,7 @@ def StartObjectsVector(builder, numElems: int) -> int:
def SchemaAddEnums(builder, enums): def SchemaAddEnums(builder, enums):
builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(enums), 0) builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(enums), 0)
def AddEnums(builder: flatbuffers.Builder, enums: int): def AddEnums(builder, enums):
SchemaAddEnums(builder, enums) SchemaAddEnums(builder, enums)
def SchemaStartEnumsVector(builder, numElems): def SchemaStartEnumsVector(builder, numElems):
@@ -195,25 +195,25 @@ def StartEnumsVector(builder, numElems: int) -> int:
def SchemaAddFileIdent(builder, fileIdent): def SchemaAddFileIdent(builder, fileIdent):
builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(fileIdent), 0) builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(fileIdent), 0)
def AddFileIdent(builder: flatbuffers.Builder, fileIdent: int): def AddFileIdent(builder, fileIdent):
SchemaAddFileIdent(builder, fileIdent) SchemaAddFileIdent(builder, fileIdent)
def SchemaAddFileExt(builder, fileExt): def SchemaAddFileExt(builder, fileExt):
builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(fileExt), 0) builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(fileExt), 0)
def AddFileExt(builder: flatbuffers.Builder, fileExt: int): def AddFileExt(builder, fileExt):
SchemaAddFileExt(builder, fileExt) SchemaAddFileExt(builder, fileExt)
def SchemaAddRootTable(builder, rootTable): def SchemaAddRootTable(builder, rootTable):
builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(rootTable), 0) builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(rootTable), 0)
def AddRootTable(builder: flatbuffers.Builder, rootTable: int): def AddRootTable(builder, rootTable):
SchemaAddRootTable(builder, rootTable) SchemaAddRootTable(builder, rootTable)
def SchemaAddServices(builder, services): def SchemaAddServices(builder, services):
builder.PrependUOffsetTRelativeSlot(5, flatbuffers.number_types.UOffsetTFlags.py_type(services), 0) builder.PrependUOffsetTRelativeSlot(5, flatbuffers.number_types.UOffsetTFlags.py_type(services), 0)
def AddServices(builder: flatbuffers.Builder, services: int): def AddServices(builder, services):
SchemaAddServices(builder, services) SchemaAddServices(builder, services)
def SchemaStartServicesVector(builder, numElems): def SchemaStartServicesVector(builder, numElems):
@@ -225,13 +225,13 @@ def StartServicesVector(builder, numElems: int) -> int:
def SchemaAddAdvancedFeatures(builder, advancedFeatures): def SchemaAddAdvancedFeatures(builder, advancedFeatures):
builder.PrependUint64Slot(6, advancedFeatures, 0) builder.PrependUint64Slot(6, advancedFeatures, 0)
def AddAdvancedFeatures(builder: flatbuffers.Builder, advancedFeatures: int): def AddAdvancedFeatures(builder, advancedFeatures):
SchemaAddAdvancedFeatures(builder, advancedFeatures) SchemaAddAdvancedFeatures(builder, advancedFeatures)
def SchemaAddFbsFiles(builder, fbsFiles): def SchemaAddFbsFiles(builder, fbsFiles):
builder.PrependUOffsetTRelativeSlot(7, flatbuffers.number_types.UOffsetTFlags.py_type(fbsFiles), 0) builder.PrependUOffsetTRelativeSlot(7, flatbuffers.number_types.UOffsetTFlags.py_type(fbsFiles), 0)
def AddFbsFiles(builder: flatbuffers.Builder, fbsFiles: int): def AddFbsFiles(builder, fbsFiles):
SchemaAddFbsFiles(builder, fbsFiles) SchemaAddFbsFiles(builder, fbsFiles)
def SchemaStartFbsFilesVector(builder, numElems): def SchemaStartFbsFilesVector(builder, numElems):

View File

@@ -69,13 +69,13 @@ def Start(builder):
def SchemaFileAddFilename(builder, filename): def SchemaFileAddFilename(builder, filename):
builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(filename), 0) builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(filename), 0)
def AddFilename(builder: flatbuffers.Builder, filename: int): def AddFilename(builder, filename):
SchemaFileAddFilename(builder, filename) SchemaFileAddFilename(builder, filename)
def SchemaFileAddIncludedFilenames(builder, includedFilenames): def SchemaFileAddIncludedFilenames(builder, includedFilenames):
builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(includedFilenames), 0) builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(includedFilenames), 0)
def AddIncludedFilenames(builder: flatbuffers.Builder, includedFilenames: int): def AddIncludedFilenames(builder, includedFilenames):
SchemaFileAddIncludedFilenames(builder, includedFilenames) SchemaFileAddIncludedFilenames(builder, includedFilenames)
def SchemaFileStartIncludedFilenamesVector(builder, numElems): def SchemaFileStartIncludedFilenamesVector(builder, numElems):

View File

@@ -42,7 +42,7 @@ class Service(object):
x = self._tab.Vector(o) x = self._tab.Vector(o)
x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
x = self._tab.Indirect(x) x = self._tab.Indirect(x)
from .reflection.RPCCall import RPCCall from reflection.RPCCall import RPCCall
obj = RPCCall() obj = RPCCall()
obj.Init(self._tab.Bytes, x) obj.Init(self._tab.Bytes, x)
return obj return obj
@@ -67,7 +67,7 @@ class Service(object):
x = self._tab.Vector(o) x = self._tab.Vector(o)
x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4
x = self._tab.Indirect(x) x = self._tab.Indirect(x)
from .reflection.KeyValue import KeyValue from reflection.KeyValue import KeyValue
obj = KeyValue() obj = KeyValue()
obj.Init(self._tab.Bytes, x) obj.Init(self._tab.Bytes, x)
return obj return obj
@@ -122,13 +122,13 @@ def Start(builder):
def ServiceAddName(builder, name): def ServiceAddName(builder, name):
builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0) builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0)
def AddName(builder: flatbuffers.Builder, name: int): def AddName(builder, name):
ServiceAddName(builder, name) ServiceAddName(builder, name)
def ServiceAddCalls(builder, calls): def ServiceAddCalls(builder, calls):
builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(calls), 0) builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(calls), 0)
def AddCalls(builder: flatbuffers.Builder, calls: int): def AddCalls(builder, calls):
ServiceAddCalls(builder, calls) ServiceAddCalls(builder, calls)
def ServiceStartCallsVector(builder, numElems): def ServiceStartCallsVector(builder, numElems):
@@ -140,7 +140,7 @@ def StartCallsVector(builder, numElems: int) -> int:
def ServiceAddAttributes(builder, attributes): def ServiceAddAttributes(builder, attributes):
builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(attributes), 0) builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(attributes), 0)
def AddAttributes(builder: flatbuffers.Builder, attributes: int): def AddAttributes(builder, attributes):
ServiceAddAttributes(builder, attributes) ServiceAddAttributes(builder, attributes)
def ServiceStartAttributesVector(builder, numElems): def ServiceStartAttributesVector(builder, numElems):
@@ -152,7 +152,7 @@ def StartAttributesVector(builder, numElems: int) -> int:
def ServiceAddDocumentation(builder, documentation): def ServiceAddDocumentation(builder, documentation):
builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(documentation), 0) builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(documentation), 0)
def AddDocumentation(builder: flatbuffers.Builder, documentation: int): def AddDocumentation(builder, documentation):
ServiceAddDocumentation(builder, documentation) ServiceAddDocumentation(builder, documentation)
def ServiceStartDocumentationVector(builder, numElems): def ServiceStartDocumentationVector(builder, numElems):
@@ -164,7 +164,7 @@ def StartDocumentationVector(builder, numElems: int) -> int:
def ServiceAddDeclarationFile(builder, declarationFile): def ServiceAddDeclarationFile(builder, declarationFile):
builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(declarationFile), 0) builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(declarationFile), 0)
def AddDeclarationFile(builder: flatbuffers.Builder, declarationFile: int): def AddDeclarationFile(builder, declarationFile):
ServiceAddDeclarationFile(builder, declarationFile) ServiceAddDeclarationFile(builder, declarationFile)
def ServiceEnd(builder): def ServiceEnd(builder):

View File

@@ -81,37 +81,37 @@ def Start(builder):
def TypeAddBaseType(builder, baseType): def TypeAddBaseType(builder, baseType):
builder.PrependInt8Slot(0, baseType, 0) builder.PrependInt8Slot(0, baseType, 0)
def AddBaseType(builder: flatbuffers.Builder, baseType: int): def AddBaseType(builder, baseType):
TypeAddBaseType(builder, baseType) TypeAddBaseType(builder, baseType)
def TypeAddElement(builder, element): def TypeAddElement(builder, element):
builder.PrependInt8Slot(1, element, 0) builder.PrependInt8Slot(1, element, 0)
def AddElement(builder: flatbuffers.Builder, element: int): def AddElement(builder, element):
TypeAddElement(builder, element) TypeAddElement(builder, element)
def TypeAddIndex(builder, index): def TypeAddIndex(builder, index):
builder.PrependInt32Slot(2, index, -1) builder.PrependInt32Slot(2, index, -1)
def AddIndex(builder: flatbuffers.Builder, index: int): def AddIndex(builder, index):
TypeAddIndex(builder, index) TypeAddIndex(builder, index)
def TypeAddFixedLength(builder, fixedLength): def TypeAddFixedLength(builder, fixedLength):
builder.PrependUint16Slot(3, fixedLength, 0) builder.PrependUint16Slot(3, fixedLength, 0)
def AddFixedLength(builder: flatbuffers.Builder, fixedLength: int): def AddFixedLength(builder, fixedLength):
TypeAddFixedLength(builder, fixedLength) TypeAddFixedLength(builder, fixedLength)
def TypeAddBaseSize(builder, baseSize): def TypeAddBaseSize(builder, baseSize):
builder.PrependUint32Slot(4, baseSize, 4) builder.PrependUint32Slot(4, baseSize, 4)
def AddBaseSize(builder: flatbuffers.Builder, baseSize: int): def AddBaseSize(builder, baseSize):
TypeAddBaseSize(builder, baseSize) TypeAddBaseSize(builder, baseSize)
def TypeAddElementSize(builder, elementSize): def TypeAddElementSize(builder, elementSize):
builder.PrependUint32Slot(5, elementSize, 0) builder.PrependUint32Slot(5, elementSize, 0)
def AddElementSize(builder: flatbuffers.Builder, elementSize: int): def AddElementSize(builder, elementSize):
TypeAddElementSize(builder, elementSize) TypeAddElementSize(builder, elementSize)
def TypeEnd(builder): def TypeEnd(builder):

View File

@@ -16,7 +16,7 @@ from setuptools import setup
setup( setup(
name='flatbuffers', name='flatbuffers',
version='23.5.8', version='23.5.26',
license='Apache 2.0', license='Apache 2.0',
license_files='../LICENSE', license_files='../LICENSE',
author='Derek Bailey', author='Derek Bailey',

View File

@@ -25,6 +25,7 @@ enum BaseType : byte {
Obj, // Used for tables & structs. Obj, // Used for tables & structs.
Union, Union,
Array, Array,
Vector64,
// Add any new type above this value. // Add any new type above this value.
MaxBaseType MaxBaseType
@@ -85,6 +86,8 @@ table Field {
optional:bool = false; optional:bool = false;
/// Number of padding octets to always add after this field. Structs only. /// Number of padding octets to always add after this field. Structs only.
padding:uint16 = 0; padding:uint16 = 0;
/// If the field uses 64-bit offsets.
offset64:bool = false;
} }
table Object { // Used for both tables and structs. table Object { // Used for both tables and structs.

View File

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

View File

@@ -10,7 +10,7 @@
// generated, otherwise it may not be compatible. // generated, otherwise it may not be compatible.
static_assert(FLATBUFFERS_VERSION_MAJOR == 23 && static_assert(FLATBUFFERS_VERSION_MAJOR == 23 &&
FLATBUFFERS_VERSION_MINOR == 5 && FLATBUFFERS_VERSION_MINOR == 5 &&
FLATBUFFERS_VERSION_REVISION == 8, FLATBUFFERS_VERSION_REVISION == 26,
"Non-compatible flatbuffers version included"); "Non-compatible flatbuffers version included");
namespace MyGame { namespace MyGame {

View File

@@ -36,7 +36,7 @@ public enum MyGame_Sample_Equipment: UInt8, UnionEnum {
public struct MyGame_Sample_Vec3: NativeStruct, Verifiable, FlatbuffersInitializable { public struct MyGame_Sample_Vec3: NativeStruct, Verifiable, FlatbuffersInitializable {
static func validateVersion() { FlatBuffersVersion_23_5_8() } static func validateVersion() { FlatBuffersVersion_23_5_26() }
private var _x: Float32 private var _x: Float32
private var _y: Float32 private var _y: Float32
@@ -72,7 +72,7 @@ public struct MyGame_Sample_Vec3: NativeStruct, Verifiable, FlatbuffersInitializ
public struct MyGame_Sample_Vec3_Mutable: FlatBufferObject { public struct MyGame_Sample_Vec3_Mutable: FlatBufferObject {
static func validateVersion() { FlatBuffersVersion_23_5_8() } static func validateVersion() { FlatBuffersVersion_23_5_26() }
public var __buffer: ByteBuffer! { return _accessor.bb } public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Struct private var _accessor: Struct
@@ -88,7 +88,7 @@ public struct MyGame_Sample_Vec3_Mutable: FlatBufferObject {
public struct MyGame_Sample_Monster: FlatBufferObject, Verifiable { public struct MyGame_Sample_Monster: FlatBufferObject, Verifiable {
static func validateVersion() { FlatBuffersVersion_23_5_8() } static func validateVersion() { FlatBuffersVersion_23_5_26() }
public var __buffer: ByteBuffer! { return _accessor.bb } public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table private var _accessor: Table
@@ -200,7 +200,7 @@ public struct MyGame_Sample_Monster: FlatBufferObject, Verifiable {
public struct MyGame_Sample_Weapon: FlatBufferObject, Verifiable { public struct MyGame_Sample_Weapon: FlatBufferObject, Verifiable {
static func validateVersion() { FlatBuffersVersion_23_5_8() } static func validateVersion() { FlatBuffersVersion_23_5_26() }
public var __buffer: ByteBuffer! { return _accessor.bb } public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table private var _accessor: Table

View File

@@ -59,13 +59,13 @@ int main(int /*argc*/, const char * /*argv*/[]) {
// to ensure it is correct, we now generate text back from the binary, // to ensure it is correct, we now generate text back from the binary,
// and compare the two: // and compare the two:
std::string jsongen1; std::string jsongen1;
if (GenerateText(parser1, parser1.builder_.GetBufferPointer(), &jsongen1)) { if (GenText(parser1, parser1.builder_.GetBufferPointer(), &jsongen1)) {
printf("Couldn't serialize parsed data to JSON!\n"); printf("Couldn't serialize parsed data to JSON!\n");
return 1; return 1;
} }
std::string jsongen2; std::string jsongen2;
if (GenerateText(parser2, parser2.builder_.GetBufferPointer(), &jsongen2)) { if (GenText(parser2, parser2.builder_.GetBufferPointer(), &jsongen2)) {
printf("Couldn't serialize parsed data to JSON!\n"); printf("Couldn't serialize parsed data to JSON!\n");
return 1; return 1;
} }

View File

@@ -45,7 +45,7 @@ int main(int /*argc*/, const char * /*argv*/[]) {
// to ensure it is correct, we now generate text back from the binary, // to ensure it is correct, we now generate text back from the binary,
// and compare the two: // and compare the two:
std::string jsongen; std::string jsongen;
if (GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen)) { if (GenText(parser, parser.builder_.GetBufferPointer(), &jsongen)) {
printf("Couldn't serialize parsed data to JSON!\n"); printf("Couldn't serialize parsed data to JSON!\n");
return 1; return 1;
} }

View File

@@ -339,6 +339,12 @@ flatc(
schema="arrays_test.fbs", schema="arrays_test.fbs",
) )
flatc(
RUST_OPTS,
prefix="rust_namer_test",
schema="rust_namer_test.fbs",
)
flatc( flatc(
BASE_OPTS + PYTHON_OPTS, BASE_OPTS + PYTHON_OPTS,
schema="arrays_test.fbs", schema="arrays_test.fbs",

View File

@@ -125,8 +125,6 @@ cc_library(
"idl_gen_kotlin.h", "idl_gen_kotlin.h",
"idl_gen_lobster.cpp", "idl_gen_lobster.cpp",
"idl_gen_lobster.h", "idl_gen_lobster.h",
"idl_gen_lua.cpp",
"idl_gen_lua.h",
"idl_gen_php.cpp", "idl_gen_php.cpp",
"idl_gen_php.h", "idl_gen_php.h",
"idl_gen_python.cpp", "idl_gen_python.cpp",

View File

@@ -1,6 +1,7 @@
#include "annotated_binary_text_gen.h" #include "annotated_binary_text_gen.h"
#include <algorithm> #include <algorithm>
#include <cstdint>
#include <fstream> #include <fstream>
#include <ostream> #include <ostream>
#include <sstream> #include <sstream>
@@ -36,6 +37,7 @@ static std::string ToString(const BinarySectionType type) {
case BinarySectionType::Struct: return "struct"; case BinarySectionType::Struct: return "struct";
case BinarySectionType::String: return "string"; case BinarySectionType::String: return "string";
case BinarySectionType::Vector: return "vector"; case BinarySectionType::Vector: return "vector";
case BinarySectionType::Vector64: return "vector64";
case BinarySectionType::Unknown: return "unknown"; case BinarySectionType::Unknown: return "unknown";
case BinarySectionType::Union: return "union"; case BinarySectionType::Union: return "union";
case BinarySectionType::Padding: return "padding"; case BinarySectionType::Padding: return "padding";
@@ -44,7 +46,9 @@ static std::string ToString(const BinarySectionType type) {
} }
static bool IsOffset(const BinaryRegionType type) { static bool IsOffset(const BinaryRegionType type) {
return type == BinaryRegionType::UOffset || type == BinaryRegionType::SOffset; return type == BinaryRegionType::UOffset ||
type == BinaryRegionType::SOffset ||
type == BinaryRegionType::UOffset64;
} }
template<typename T> std::string ToString(T value) { template<typename T> std::string ToString(T value) {
@@ -119,6 +123,9 @@ static std::string ToValueString(const BinaryRegion &region,
case BinaryRegionType::UType: return ToValueString<uint8_t>(region, binary); case BinaryRegionType::UType: return ToValueString<uint8_t>(region, binary);
// Handle Offsets separately, incase they add additional details. // Handle Offsets separately, incase they add additional details.
case BinaryRegionType::UOffset64:
s += ToValueString<uint64_t>(region, binary);
break;
case BinaryRegionType::UOffset: case BinaryRegionType::UOffset:
s += ToValueString<uint32_t>(region, binary); s += ToValueString<uint32_t>(region, binary);
break; break;
@@ -368,7 +375,8 @@ static void GenerateSection(std::ostream &os, const BinarySection &section,
// As a space saving measure, skip generating every vector element, just put // As a space saving measure, skip generating every vector element, just put
// the first and last elements in the output. Skip the whole thing if there // the first and last elements in the output. Skip the whole thing if there
// are only three or fewer elements, as it doesn't save space. // are only three or fewer elements, as it doesn't save space.
if (section.type == BinarySectionType::Vector && if ((section.type == BinarySectionType::Vector ||
section.type == BinarySectionType::Vector64) &&
!output_config.include_vector_contents && section.regions.size() > 4) { !output_config.include_vector_contents && section.regions.size() > 4) {
// Generate the length region which should be first. // Generate the length region which should be first.
GenerateRegion(os, section.regions[0], section, binary, output_config); GenerateRegion(os, section.regions[0], section, binary, output_config);

View File

@@ -101,15 +101,15 @@ class BaseBfbsGenerator : public CodeGenerator {
virtual ~BaseBfbsGenerator() {} virtual ~BaseBfbsGenerator() {}
BaseBfbsGenerator() : schema_(nullptr) {} BaseBfbsGenerator() : schema_(nullptr) {}
virtual Status GenerateFromSchema( virtual Status GenerateFromSchema(const reflection::Schema *schema,
const reflection::Schema *schema) = 0; const CodeGenOptions &options) = 0;
virtual uint64_t SupportedAdvancedFeatures() const = 0; virtual uint64_t SupportedAdvancedFeatures() const = 0;
// Override of the Generator::GenerateCode method that does the initial // Override of the Generator::GenerateCode method that does the initial
// deserialization and verification steps. // deserialization and verification steps.
Status GenerateCode(const uint8_t *buffer, Status GenerateCode(const uint8_t *buffer, int64_t length,
int64_t length) FLATBUFFERS_OVERRIDE { const CodeGenOptions &options) FLATBUFFERS_OVERRIDE {
flatbuffers::Verifier verifier(buffer, static_cast<size_t>(length)); flatbuffers::Verifier verifier(buffer, static_cast<size_t>(length));
if (!reflection::VerifySchemaBuffer(verifier)) { if (!reflection::VerifySchemaBuffer(verifier)) {
return FAILED_VERIFICATION; return FAILED_VERIFICATION;
@@ -124,7 +124,7 @@ class BaseBfbsGenerator : public CodeGenerator {
return FAILED_VERIFICATION; return FAILED_VERIFICATION;
} }
Status status = GenerateFromSchema(schema_); Status status = GenerateFromSchema(schema_, options);
schema_ = nullptr; schema_ = nullptr;
return status; return status;
} }

View File

@@ -28,6 +28,7 @@
#include "bfbs_namer.h" #include "bfbs_namer.h"
// The intermediate representation schema. // The intermediate representation schema.
#include "flatbuffers/code_generator.h"
#include "flatbuffers/reflection.h" #include "flatbuffers/reflection.h"
#include "flatbuffers/reflection_generated.h" #include "flatbuffers/reflection_generated.h"
@@ -78,7 +79,10 @@ class LuaBfbsGenerator : public BaseBfbsGenerator {
flatc_version_(flatc_version), flatc_version_(flatc_version),
namer_(LuaDefaultConfig(), LuaKeywords()) {} namer_(LuaDefaultConfig(), LuaKeywords()) {}
Status GenerateFromSchema(const r::Schema *schema) FLATBUFFERS_OVERRIDE { Status GenerateFromSchema(const r::Schema *schema,
const CodeGenOptions &options)
FLATBUFFERS_OVERRIDE {
options_ = options;
if (!GenerateEnums(schema->enums())) { return ERROR; } if (!GenerateEnums(schema->enums())) { return ERROR; }
if (!GenerateObjects(schema->objects(), schema->root_table())) { if (!GenerateObjects(schema->objects(), schema->root_table())) {
return ERROR; return ERROR;
@@ -88,10 +92,9 @@ class LuaBfbsGenerator : public BaseBfbsGenerator {
using BaseBfbsGenerator::GenerateCode; using BaseBfbsGenerator::GenerateCode;
Status GenerateCode(const Parser &parser, const std::string &path, Status GenerateCode(const Parser &, const std::string &,
const std::string &filename) FLATBUFFERS_OVERRIDE { const std::string &) override {
if (!GenerateLua(parser, path, filename)) { return ERROR; } return Status::NOT_IMPLEMENTED;
return OK;
} }
Status GenerateMakeRule(const Parser &parser, const std::string &path, Status GenerateMakeRule(const Parser &parser, const std::string &path,
@@ -653,12 +656,15 @@ class LuaBfbsGenerator : public BaseBfbsGenerator {
// TODO(derekbailey): figure out a save file without depending on util.h // TODO(derekbailey): figure out a save file without depending on util.h
EnsureDirExists(path); EnsureDirExists(path);
const std::string file_name = path + "/" + namer_.File(name); const std::string file_name =
options_.output_path + path + "/" + namer_.File(name);
SaveFile(file_name.c_str(), code, false); SaveFile(file_name.c_str(), code, false);
} }
std::unordered_set<std::string> keywords_; std::unordered_set<std::string> keywords_;
std::map<std::string, std::string> requires_; std::map<std::string, std::string> requires_;
CodeGenOptions options_;
const r::Object *current_obj_; const r::Object *current_obj_;
const r::Enum *current_enum_; const r::Enum *current_enum_;
const std::string flatc_version_; const std::string flatc_version_;

View File

@@ -28,6 +28,7 @@
#include "bfbs_namer.h" #include "bfbs_namer.h"
// The intermediate representation schema. // The intermediate representation schema.
#include "flatbuffers/code_generator.h"
#include "flatbuffers/reflection.h" #include "flatbuffers/reflection.h"
#include "flatbuffers/reflection_generated.h" #include "flatbuffers/reflection_generated.h"
@@ -95,7 +96,10 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
flatc_version_(flatc_version), flatc_version_(flatc_version),
namer_(NimDefaultConfig(), NimKeywords()) {} namer_(NimDefaultConfig(), NimKeywords()) {}
Status GenerateFromSchema(const r::Schema *schema) FLATBUFFERS_OVERRIDE { Status GenerateFromSchema(const r::Schema *schema,
const CodeGenOptions &options)
FLATBUFFERS_OVERRIDE {
options_ = options;
ForAllEnums(schema->enums(), [&](const r::Enum *enum_def) { ForAllEnums(schema->enums(), [&](const r::Enum *enum_def) {
StartCodeBlock(enum_def); StartCodeBlock(enum_def);
GenerateEnum(enum_def); GenerateEnum(enum_def);
@@ -671,12 +675,15 @@ class NimBfbsGenerator : public BaseBfbsGenerator {
// TODO(derekbailey): figure out a save file without depending on util.h // TODO(derekbailey): figure out a save file without depending on util.h
EnsureDirExists(path); EnsureDirExists(path);
const std::string file_name = path + "/" + namer_.File(name); const std::string file_name =
options_.output_path + path + "/" + namer_.File(name);
SaveFile(file_name.c_str(), code, false); SaveFile(file_name.c_str(), code, false);
} }
std::unordered_set<std::string> keywords_; std::unordered_set<std::string> keywords_;
std::map<std::string, std::string> imports_; std::map<std::string, std::string> imports_;
CodeGenOptions options_;
const r::Object *current_obj_; const r::Object *current_obj_;
const r::Enum *current_enum_; const r::Enum *current_enum_;
const std::string flatc_version_; const std::string flatc_version_;

View File

@@ -1,10 +1,13 @@
#include "binary_annotator.h" #include "binary_annotator.h"
#include <algorithm> #include <algorithm>
#include <cstdint>
#include <iostream>
#include <limits> #include <limits>
#include <string> #include <string>
#include <vector> #include <vector>
#include "flatbuffers/base.h"
#include "flatbuffers/reflection.h" #include "flatbuffers/reflection.h"
#include "flatbuffers/util.h" #include "flatbuffers/util.h"
#include "flatbuffers/verifier.h" #include "flatbuffers/verifier.h"
@@ -37,9 +40,9 @@ static BinaryRegion MakeBinaryRegion(
return region; return region;
} }
static BinarySection MakeBinarySection( static BinarySection MakeBinarySection(const std::string &name,
const std::string &name, const BinarySectionType type, const BinarySectionType type,
std::vector<BinaryRegion> regions) { std::vector<BinaryRegion> regions) {
BinarySection section; BinarySection section;
section.name = name; section.name = name;
section.type = type; section.type = type;
@@ -118,12 +121,15 @@ static BinarySection GenerateMissingSection(const uint64_t offset,
std::map<uint64_t, BinarySection> BinaryAnnotator::Annotate() { std::map<uint64_t, BinarySection> BinaryAnnotator::Annotate() {
flatbuffers::Verifier verifier(bfbs_, static_cast<size_t>(bfbs_length_)); flatbuffers::Verifier verifier(bfbs_, static_cast<size_t>(bfbs_length_));
if (!reflection::VerifySchemaBuffer(verifier)) { return {}; }
if ((is_size_prefixed_ &&
!reflection::VerifySizePrefixedSchemaBuffer(verifier)) ||
!reflection::VerifySchemaBuffer(verifier)) {
return {};
}
// The binary is too short to read as a flatbuffers. // The binary is too short to read as a flatbuffers.
// TODO(dbaileychess): We could spit out the annotated buffer sections, but if (binary_length_ < FLATBUFFERS_MIN_BUFFER_SIZE) { return {}; }
// I'm not sure if it is worth it.
if (binary_length_ < 4) { return {}; }
// Make sure we start with a clean slate. // Make sure we start with a clean slate.
vtables_.clear(); vtables_.clear();
@@ -151,7 +157,41 @@ std::map<uint64_t, BinarySection> BinaryAnnotator::Annotate() {
} }
uint64_t BinaryAnnotator::BuildHeader(const uint64_t header_offset) { uint64_t BinaryAnnotator::BuildHeader(const uint64_t header_offset) {
const auto root_table_offset = ReadScalar<uint32_t>(header_offset); uint64_t offset = header_offset;
std::vector<BinaryRegion> regions;
// If this binary is a size prefixed one, attempt to parse the size.
if (is_size_prefixed_) {
BinaryRegionComment prefix_length_comment;
prefix_length_comment.type = BinaryRegionCommentType::SizePrefix;
bool has_prefix_value = false;
const auto prefix_length = ReadScalar<uoffset64_t>(offset);
if (*prefix_length <= binary_length_) {
regions.push_back(MakeBinaryRegion(offset, sizeof(uoffset64_t),
BinaryRegionType::Uint64, 0, 0,
prefix_length_comment));
offset += sizeof(uoffset64_t);
has_prefix_value = true;
}
if (!has_prefix_value) {
const auto prefix_length = ReadScalar<uoffset_t>(offset);
if (*prefix_length <= binary_length_) {
regions.push_back(MakeBinaryRegion(offset, sizeof(uoffset_t),
BinaryRegionType::Uint32, 0, 0,
prefix_length_comment));
offset += sizeof(uoffset_t);
has_prefix_value = true;
}
}
if (!has_prefix_value) {
SetError(prefix_length_comment, BinaryRegionStatus::ERROR);
}
}
const auto root_table_offset = ReadScalar<uint32_t>(offset);
if (!root_table_offset.has_value()) { if (!root_table_offset.has_value()) {
// This shouldn't occur, since we validate the min size of the buffer // This shouldn't occur, since we validate the min size of the buffer
@@ -159,22 +199,20 @@ uint64_t BinaryAnnotator::BuildHeader(const uint64_t header_offset) {
return std::numeric_limits<uint64_t>::max(); return std::numeric_limits<uint64_t>::max();
} }
std::vector<BinaryRegion> regions; const auto root_table_loc = offset + *root_table_offset;
uint64_t offset = header_offset;
// TODO(dbaileychess): sized prefixed value
BinaryRegionComment root_offset_comment; BinaryRegionComment root_offset_comment;
root_offset_comment.type = BinaryRegionCommentType::RootTableOffset; root_offset_comment.type = BinaryRegionCommentType::RootTableOffset;
root_offset_comment.name = schema_->root_table()->name()->str(); root_offset_comment.name = schema_->root_table()->name()->str();
if (!IsValidOffset(root_table_offset.value())) { if (!IsValidOffset(root_table_loc)) {
SetError(root_offset_comment, SetError(root_offset_comment,
BinaryRegionStatus::ERROR_OFFSET_OUT_OF_BINARY); BinaryRegionStatus::ERROR_OFFSET_OUT_OF_BINARY);
} }
regions.push_back( regions.push_back(MakeBinaryRegion(offset, sizeof(uint32_t),
MakeBinaryRegion(offset, sizeof(uint32_t), BinaryRegionType::UOffset, 0, BinaryRegionType::UOffset, 0,
root_table_offset.value(), root_offset_comment)); root_table_loc, root_offset_comment));
offset += sizeof(uint32_t); offset += sizeof(uint32_t);
if (IsValidRead(offset, flatbuffers::kFileIdentifierLength) && if (IsValidRead(offset, flatbuffers::kFileIdentifierLength) &&
@@ -193,7 +231,7 @@ uint64_t BinaryAnnotator::BuildHeader(const uint64_t header_offset) {
AddSection(header_offset, MakeBinarySection("", BinarySectionType::Header, AddSection(header_offset, MakeBinarySection("", BinarySectionType::Header,
std::move(regions))); std::move(regions)));
return root_table_offset.value(); return root_table_loc;
} }
BinaryAnnotator::VTable *BinaryAnnotator::GetOrBuildVTable( BinaryAnnotator::VTable *BinaryAnnotator::GetOrBuildVTable(
@@ -656,7 +694,18 @@ void BinaryAnnotator::BuildTable(const uint64_t table_offset,
} }
// Read the offset // Read the offset
const auto offset_from_field = ReadScalar<uint32_t>(field_offset); uint64_t offset = 0;
uint64_t length = sizeof(uint32_t);
BinaryRegionType region_type = BinaryRegionType::UOffset;
if (field->offset64()) {
length = sizeof(uint64_t);
region_type = BinaryRegionType::UOffset64;
offset = ReadScalar<uint64_t>(field_offset).value_or(0);
} else {
offset = ReadScalar<uint32_t>(field_offset).value_or(0);
}
// const auto offset_from_field = ReadScalar<uint32_t>(field_offset);
uint64_t offset_of_next_item = 0; uint64_t offset_of_next_item = 0;
BinaryRegionComment offset_field_comment; BinaryRegionComment offset_field_comment;
offset_field_comment.type = BinaryRegionCommentType::TableOffsetField; offset_field_comment.type = BinaryRegionCommentType::TableOffsetField;
@@ -666,7 +715,7 @@ void BinaryAnnotator::BuildTable(const uint64_t table_offset,
// Validate any field that isn't inline (i.e., non-structs). // Validate any field that isn't inline (i.e., non-structs).
if (!IsInlineField(field)) { if (!IsInlineField(field)) {
if (!offset_from_field.has_value()) { if (offset == 0) {
const uint64_t remaining = RemainingBytes(field_offset); const uint64_t remaining = RemainingBytes(field_offset);
SetError(offset_field_comment, SetError(offset_field_comment,
@@ -678,14 +727,14 @@ void BinaryAnnotator::BuildTable(const uint64_t table_offset,
continue; continue;
} }
offset_of_next_item = field_offset + offset_from_field.value(); offset_of_next_item = field_offset + offset;
if (!IsValidOffset(offset_of_next_item)) { if (!IsValidOffset(offset_of_next_item)) {
SetError(offset_field_comment, SetError(offset_field_comment,
BinaryRegionStatus::ERROR_OFFSET_OUT_OF_BINARY); BinaryRegionStatus::ERROR_OFFSET_OUT_OF_BINARY);
regions.push_back(MakeBinaryRegion( regions.push_back(MakeBinaryRegion(field_offset, length, region_type, 0,
field_offset, sizeof(uint32_t), BinaryRegionType::UOffset, 0, offset_of_next_item,
offset_of_next_item, offset_field_comment)); offset_field_comment));
continue; continue;
} }
} }
@@ -702,9 +751,9 @@ void BinaryAnnotator::BuildTable(const uint64_t table_offset,
} else { } else {
offset_field_comment.default_value = "(table)"; offset_field_comment.default_value = "(table)";
regions.push_back(MakeBinaryRegion( regions.push_back(MakeBinaryRegion(field_offset, length, region_type,
field_offset, sizeof(uint32_t), BinaryRegionType::UOffset, 0, 0, offset_of_next_item,
offset_of_next_item, offset_field_comment)); offset_field_comment));
BuildTable(offset_of_next_item, BinarySectionType::Table, BuildTable(offset_of_next_item, BinarySectionType::Table,
next_object); next_object);
@@ -713,17 +762,25 @@ void BinaryAnnotator::BuildTable(const uint64_t table_offset,
case reflection::BaseType::String: { case reflection::BaseType::String: {
offset_field_comment.default_value = "(string)"; offset_field_comment.default_value = "(string)";
regions.push_back(MakeBinaryRegion( regions.push_back(MakeBinaryRegion(field_offset, length, region_type, 0,
field_offset, sizeof(uint32_t), BinaryRegionType::UOffset, 0, offset_of_next_item,
offset_of_next_item, offset_field_comment)); offset_field_comment));
BuildString(offset_of_next_item, table, field); BuildString(offset_of_next_item, table, field);
} break; } break;
case reflection::BaseType::Vector: { case reflection::BaseType::Vector: {
offset_field_comment.default_value = "(vector)"; offset_field_comment.default_value = "(vector)";
regions.push_back(MakeBinaryRegion( regions.push_back(MakeBinaryRegion(field_offset, length, region_type, 0,
field_offset, sizeof(uint32_t), BinaryRegionType::UOffset, 0, offset_of_next_item,
offset_of_next_item, offset_field_comment)); offset_field_comment));
BuildVector(offset_of_next_item, table, field, table_offset,
vtable->fields);
} break;
case reflection::BaseType::Vector64: {
offset_field_comment.default_value = "(vector64)";
regions.push_back(MakeBinaryRegion(field_offset, length, region_type, 0,
offset_of_next_item,
offset_field_comment));
BuildVector(offset_of_next_item, table, field, table_offset, BuildVector(offset_of_next_item, table, field, table_offset,
vtable->fields); vtable->fields);
} break; } break;
@@ -768,8 +825,7 @@ void BinaryAnnotator::BuildTable(const uint64_t table_offset,
offset_field_comment.default_value = offset_field_comment.default_value =
"(union of type `" + enum_type + "`)"; "(union of type `" + enum_type + "`)";
regions.push_back(MakeBinaryRegion(field_offset, sizeof(uint32_t), regions.push_back(MakeBinaryRegion(field_offset, length, region_type, 0,
BinaryRegionType::UOffset, 0,
union_offset, offset_field_comment)); union_offset, offset_field_comment));
} break; } break;
@@ -986,7 +1042,28 @@ void BinaryAnnotator::BuildVector(
BinaryRegionComment vector_length_comment; BinaryRegionComment vector_length_comment;
vector_length_comment.type = BinaryRegionCommentType::VectorLength; vector_length_comment.type = BinaryRegionCommentType::VectorLength;
const auto vector_length = ReadScalar<uint32_t>(vector_offset); const bool is_64_bit_vector =
field->type()->base_type() == reflection::BaseType::Vector64;
flatbuffers::Optional<uint64_t> vector_length;
uint32_t vector_length_size_type = 0;
BinaryRegionType region_type = BinaryRegionType::Uint32;
BinarySectionType section_type = BinarySectionType::Vector;
if (is_64_bit_vector) {
auto v = ReadScalar<uint64_t>(vector_offset);
if (v.has_value()) { vector_length = v.value(); }
vector_length_size_type = sizeof(uint64_t);
region_type = BinaryRegionType::Uint64;
section_type = BinarySectionType::Vector64;
} else {
auto v = ReadScalar<uint32_t>(vector_offset);
if (v.has_value()) { vector_length = v.value(); }
vector_length_size_type = sizeof(uint32_t);
region_type = BinaryRegionType::Uint32;
section_type = BinarySectionType::Vector;
}
if (!vector_length.has_value()) { if (!vector_length.has_value()) {
const uint64_t remaining = RemainingBytes(vector_offset); const uint64_t remaining = RemainingBytes(vector_offset);
SetError(vector_length_comment, BinaryRegionStatus::ERROR_INCOMPLETE_BINARY, SetError(vector_length_comment, BinaryRegionStatus::ERROR_INCOMPLETE_BINARY,
@@ -1006,7 +1083,7 @@ void BinaryAnnotator::BuildVector(
// Validate there are enough bytes left in the binary to process all the // Validate there are enough bytes left in the binary to process all the
// items. // items.
const uint64_t last_item_offset = const uint64_t last_item_offset =
vector_offset + sizeof(uint32_t) + vector_offset + vector_length_size_type +
vector_length.value() * GetElementSize(field); vector_length.value() * GetElementSize(field);
if (!IsValidOffset(last_item_offset - 1)) { if (!IsValidOffset(last_item_offset - 1)) {
@@ -1016,20 +1093,18 @@ void BinaryAnnotator::BuildVector(
MakeSingleRegionBinarySection( MakeSingleRegionBinarySection(
std::string(table->name()->c_str()) + "." + field->name()->c_str(), std::string(table->name()->c_str()) + "." + field->name()->c_str(),
BinarySectionType::Vector, BinarySectionType::Vector,
MakeBinaryRegion(vector_offset, sizeof(uint32_t), MakeBinaryRegion(vector_offset, vector_length_size_type,
BinaryRegionType::Uint32, 0, 0, region_type, 0, 0, vector_length_comment)));
vector_length_comment)));
return; return;
} }
std::vector<BinaryRegion> regions; std::vector<BinaryRegion> regions;
regions.push_back(MakeBinaryRegion(vector_offset, sizeof(uint32_t), regions.push_back(MakeBinaryRegion(vector_offset, vector_length_size_type,
BinaryRegionType::Uint32, 0, 0, region_type, 0, 0, vector_length_comment));
vector_length_comment));
// Consume the vector length offset. // Consume the vector length offset.
uint64_t offset = vector_offset + sizeof(uint32_t); uint64_t offset = vector_offset + vector_length_size_type;
switch (field->type()->element()) { switch (field->type()->element()) {
case reflection::BaseType::Obj: { case reflection::BaseType::Obj: {
@@ -1302,7 +1377,7 @@ void BinaryAnnotator::BuildVector(
AddSection(vector_offset, AddSection(vector_offset,
MakeBinarySection(std::string(table->name()->c_str()) + "." + MakeBinarySection(std::string(table->name()->c_str()) + "." +
field->name()->c_str(), field->name()->c_str(),
BinarySectionType::Vector, std::move(regions))); section_type, std::move(regions)));
} }
std::string BinaryAnnotator::BuildUnion(const uint64_t union_offset, std::string BinaryAnnotator::BuildUnion(const uint64_t union_offset,

View File

@@ -48,6 +48,7 @@ enum class BinaryRegionType {
Float = 15, Float = 15,
Double = 16, Double = 16,
UType = 17, UType = 17,
UOffset64 = 18,
}; };
template<typename T> template<typename T>
@@ -179,6 +180,7 @@ enum class BinarySectionType {
Vector = 7, Vector = 7,
Union = 8, Union = 8,
Padding = 9, Padding = 9,
Vector64 = 10,
}; };
// A section of the binary that is grouped together in some logical manner, and // A section of the binary that is grouped together in some logical manner, and
@@ -216,6 +218,7 @@ inline static BinaryRegionType GetRegionType(reflection::BaseType base_type) {
inline static std::string ToString(const BinaryRegionType type) { inline static std::string ToString(const BinaryRegionType type) {
switch (type) { switch (type) {
case BinaryRegionType::UOffset: return "UOffset32"; case BinaryRegionType::UOffset: return "UOffset32";
case BinaryRegionType::UOffset64: return "UOffset64";
case BinaryRegionType::SOffset: return "SOffset32"; case BinaryRegionType::SOffset: return "SOffset32";
case BinaryRegionType::VOffset: return "VOffset16"; case BinaryRegionType::VOffset: return "VOffset16";
case BinaryRegionType::Bool: return "bool"; case BinaryRegionType::Bool: return "bool";
@@ -242,12 +245,14 @@ class BinaryAnnotator {
explicit BinaryAnnotator(const uint8_t *const bfbs, explicit BinaryAnnotator(const uint8_t *const bfbs,
const uint64_t bfbs_length, const uint64_t bfbs_length,
const uint8_t *const binary, const uint8_t *const binary,
const uint64_t binary_length) const uint64_t binary_length,
const bool is_size_prefixed)
: bfbs_(bfbs), : bfbs_(bfbs),
bfbs_length_(bfbs_length), bfbs_length_(bfbs_length),
schema_(reflection::GetSchema(bfbs)), schema_(reflection::GetSchema(bfbs)),
binary_(binary), binary_(binary),
binary_length_(binary_length) {} binary_length_(binary_length),
is_size_prefixed_(is_size_prefixed) {}
std::map<uint64_t, BinarySection> Annotate(); std::map<uint64_t, BinarySection> Annotate();
@@ -387,6 +392,7 @@ class BinaryAnnotator {
// The binary data itself. // The binary data itself.
const uint8_t *binary_; const uint8_t *binary_;
const uint64_t binary_length_; const uint64_t binary_length_;
const bool is_size_prefixed_;
// Map of binary offset to vtables, to dedupe vtables. // Map of binary offset to vtables, to dedupe vtables.
std::map<uint64_t, std::list<VTable>> vtables_; std::map<uint64_t, std::list<VTable>> vtables_;

View File

@@ -30,9 +30,7 @@
namespace flatbuffers { namespace flatbuffers {
namespace { std::string JavaCSharpMakeRule(const bool java, const Parser &parser,
static std::string JavaCSharpMakeRule(const bool java, const Parser &parser,
const std::string &path, const std::string &path,
const std::string &file_name) { const std::string &file_name) {
const std::string file_extension = java ? ".java" : ".cs"; const std::string file_extension = java ? ".java" : ".cs";
@@ -64,18 +62,6 @@ static std::string JavaCSharpMakeRule(const bool java, const Parser &parser,
return make_rule; return make_rule;
} }
static std::string BinaryFileName(const Parser &parser, const std::string &path,
const std::string &file_name) {
auto ext = parser.file_extension_.length() ? parser.file_extension_ : "bin";
return path + file_name + "." + ext;
}
} // namespace
void CodeWriter::operator+=(std::string text) { void CodeWriter::operator+=(std::string text) {
if (!ignore_ident_ && !text.empty()) AppendIdent(stream_); if (!ignore_ident_ && !text.empty()) AppendIdent(stream_);
@@ -346,48 +332,6 @@ std::string SimpleFloatConstantGenerator::NaN(float v) const {
return this->NaN(static_cast<double>(v)); return this->NaN(static_cast<double>(v));
} }
std::string JavaMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name) {
return JavaCSharpMakeRule(true, parser, path, file_name);
}
std::string CSharpMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name) {
return JavaCSharpMakeRule(false, parser, path, file_name);
}
bool GenerateBinary(const Parser &parser, const std::string &path,
const std::string &file_name) {
if (parser.opts.use_flexbuffers) {
auto data_vec = parser.flex_builder_.GetBuffer();
auto data_ptr = reinterpret_cast<char *>(data(data_vec));
return !parser.flex_builder_.GetSize() ||
flatbuffers::SaveFile(
BinaryFileName(parser, path, file_name).c_str(), data_ptr,
parser.flex_builder_.GetSize(), true);
}
return !parser.builder_.GetSize() ||
flatbuffers::SaveFile(
BinaryFileName(parser, path, file_name).c_str(),
reinterpret_cast<char *>(parser.builder_.GetBufferPointer()),
parser.builder_.GetSize(), true);
}
std::string BinaryMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name) {
if (!parser.builder_.GetSize()) return "";
std::string filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
std::string make_rule =
BinaryFileName(parser, path, filebase) + ": " + file_name;
auto included_files =
parser.GetIncludedFilesRecursive(parser.root_struct_def_->file);
for (auto it = included_files.begin(); it != included_files.end(); ++it) {
make_rule += " " + *it;
}
return make_rule;
}
} // namespace flatbuffers } // namespace flatbuffers
#if defined(_MSC_VER) #if defined(_MSC_VER)

View File

@@ -37,8 +37,8 @@ class FileNameSavingFileManager : public FileManager {
} }
bool Loadfile(const std::string &absolute_file_name, std::string *content) { bool Loadfile(const std::string &absolute_file_name, std::string *content) {
(void) absolute_file_name; (void)absolute_file_name;
(void) content; (void)content;
return false; return false;
} }

View File

@@ -252,10 +252,9 @@ const static FlatCOption flatc_options[] = {
"Currently this is required to generate private types in Rust" }, "Currently this is required to generate private types in Rust" },
{ "", "python-no-type-prefix-suffix", "", { "", "python-no-type-prefix-suffix", "",
"Skip emission of Python functions that are prefixed with typenames" }, "Skip emission of Python functions that are prefixed with typenames" },
{ "", "python-typing", "", { "", "python-typing", "", "Generate Python type annotations" },
"Generate Python type annotations" },
{ "", "file-names-only", "", { "", "file-names-only", "",
"Print out generated file names without writing to the files"}, "Print out generated file names without writing to the files" },
}; };
auto cmp = [](FlatCOption a, FlatCOption b) { return a.long_opt < b.long_opt; }; auto cmp = [](FlatCOption a, FlatCOption b) { return a.long_opt < b.long_opt; };
@@ -394,9 +393,11 @@ void FlatCompiler::AnnotateBinaries(const uint8_t *binary_schema,
const uint8_t *binary = const uint8_t *binary =
reinterpret_cast<const uint8_t *>(binary_contents.c_str()); reinterpret_cast<const uint8_t *>(binary_contents.c_str());
const size_t binary_size = binary_contents.size(); const size_t binary_size = binary_contents.size();
const bool is_size_prefixed = options.opts.size_prefixed;
flatbuffers::BinaryAnnotator binary_annotator( flatbuffers::BinaryAnnotator binary_annotator(
binary_schema, binary_schema_size, binary, binary_size); binary_schema, binary_schema_size, binary, binary_size,
is_size_prefixed);
auto annotations = binary_annotator.Annotate(); auto annotations = binary_annotator.Annotate();
@@ -663,7 +664,7 @@ FlatCOptions FlatCompiler::ParseFromCommandLineArguments(int argc,
} else if (arg == "--annotate") { } else if (arg == "--annotate") {
if (++argi >= argc) Error("missing path following: " + arg, true); if (++argi >= argc) Error("missing path following: " + arg, true);
options.annotate_schema = flatbuffers::PosixPath(argv[argi]); options.annotate_schema = flatbuffers::PosixPath(argv[argi]);
} else if(arg == "--file-names-only") { } else if (arg == "--file-names-only") {
// TODO (khhn): Provide 2 implementation // TODO (khhn): Provide 2 implementation
options.file_names_only = true; options.file_names_only = true;
} else { } else {
@@ -865,8 +866,11 @@ std::unique_ptr<Parser> FlatCompiler::GenerateCode(const FlatCOptions &options,
// Prefer bfbs generators if present. // Prefer bfbs generators if present.
if (code_generator->SupportsBfbsGeneration()) { if (code_generator->SupportsBfbsGeneration()) {
const CodeGenerator::Status status = CodeGenOptions code_gen_options;
code_generator->GenerateCode(bfbs_buffer, bfbs_length); code_gen_options.output_path = options.output_path;
const CodeGenerator::Status status = code_generator->GenerateCode(
bfbs_buffer, bfbs_length, code_gen_options);
if (status != CodeGenerator::Status::OK) { if (status != CodeGenerator::Status::OK) {
Error("Unable to generate " + code_generator->LanguageName() + Error("Unable to generate " + code_generator->LanguageName() +
" for " + filebase + code_generator->status_detail + " for " + filebase + code_generator->status_detail +
@@ -967,7 +971,7 @@ int FlatCompiler::Compile(const FlatCOptions &options) {
return 0; return 0;
} }
if (options.generators.empty()) { if (options.generators.empty() && options.conform_to_schema.empty()) {
Error("No generator registered"); Error("No generator registered");
return -1; return -1;
} }

View File

@@ -31,9 +31,46 @@
#include "flatbuffers/util.h" #include "flatbuffers/util.h"
namespace flatbuffers { namespace flatbuffers {
namespace { namespace {
static std::string BinaryFileName(const Parser &parser, const std::string &path,
const std::string &file_name) {
auto ext = parser.file_extension_.length() ? parser.file_extension_ : "bin";
return path + file_name + "." + ext;
}
static bool GenerateBinary(const Parser &parser, const std::string &path,
const std::string &file_name) {
if (parser.opts.use_flexbuffers) {
auto data_vec = parser.flex_builder_.GetBuffer();
auto data_ptr = reinterpret_cast<char *>(data(data_vec));
return !parser.flex_builder_.GetSize() ||
flatbuffers::SaveFile(
BinaryFileName(parser, path, file_name).c_str(), data_ptr,
parser.flex_builder_.GetSize(), true);
}
return !parser.builder_.GetSize() ||
flatbuffers::SaveFile(
BinaryFileName(parser, path, file_name).c_str(),
reinterpret_cast<char *>(parser.builder_.GetBufferPointer()),
parser.builder_.GetSize(), true);
}
static std::string BinaryMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name) {
if (!parser.builder_.GetSize()) return "";
std::string filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
std::string make_rule =
BinaryFileName(parser, path, filebase) + ": " + file_name;
auto included_files =
parser.GetIncludedFilesRecursive(parser.root_struct_def_->file);
for (auto it = included_files.begin(); it != included_files.end(); ++it) {
make_rule += " " + *it;
}
return make_rule;
}
class BinaryCodeGenerator : public CodeGenerator { class BinaryCodeGenerator : public CodeGenerator {
public: public:
Status GenerateCode(const Parser &parser, const std::string &path, Status GenerateCode(const Parser &parser, const std::string &path,
@@ -44,9 +81,8 @@ class BinaryCodeGenerator : public CodeGenerator {
// Generate code from the provided `buffer` of given `length`. The buffer is a // Generate code from the provided `buffer` of given `length`. The buffer is a
// serialized reflection.fbs. // serialized reflection.fbs.
Status GenerateCode(const uint8_t *buffer, int64_t length) override { Status GenerateCode(const uint8_t *, int64_t,
(void)buffer; const CodeGenOptions &) override {
(void)length;
return Status::NOT_IMPLEMENTED; return Status::NOT_IMPLEMENTED;
} }

View File

@@ -77,8 +77,7 @@ static std::string GenIncludeGuard(const std::string &file_name,
static bool IsVectorOfPointers(const FieldDef &field) { static bool IsVectorOfPointers(const FieldDef &field) {
const auto &type = field.value.type; const auto &type = field.value.type;
const auto &vector_type = type.VectorType(); const auto &vector_type = type.VectorType();
return type.base_type == BASE_TYPE_VECTOR && return IsVector(type) && vector_type.base_type == BASE_TYPE_STRUCT &&
vector_type.base_type == BASE_TYPE_STRUCT &&
!vector_type.struct_def->fixed && !field.native_inline; !vector_type.struct_def->fixed && !field.native_inline;
} }
@@ -107,6 +106,21 @@ struct IDLOptionsCpp : public IDLOptions {
: IDLOptions(opts), g_cpp_std(CPP_STD_11), g_only_fixed_enums(true) {} : IDLOptions(opts), g_cpp_std(CPP_STD_11), g_only_fixed_enums(true) {}
}; };
// Iterates over all the fields of the object first by Offset type (Offset64
// before Offset32) and then by definition order.
static void ForAllFieldsOrderedByOffset(
const StructDef &object, std::function<void(const FieldDef *field)> func) {
// Loop over all the fields and call the func on all offset64 fields.
for (const FieldDef *field_def : object.fields.vec) {
if (field_def->offset64) { func(field_def); }
}
// Loop over all the fields a second time and call the func on all offset
// fields.
for (const FieldDef *field_def : object.fields.vec) {
if (!field_def->offset64) { func(field_def); }
}
}
class CppGenerator : public BaseGenerator { class CppGenerator : public BaseGenerator {
public: public:
CppGenerator(const Parser &parser, const std::string &path, CppGenerator(const Parser &parser, const std::string &path,
@@ -273,6 +287,25 @@ class CppGenerator : public BaseGenerator {
} }
} }
void MarkIf64BitBuilderIsNeeded() {
if (needs_64_bit_builder_) { return; }
for (auto t : parser_.structs_.vec) {
if (t == nullptr) continue;
for (auto f : t->fields.vec) {
if (f == nullptr) continue;
if (f->offset64) {
needs_64_bit_builder_ = true;
break;
}
}
}
}
std::string GetBuilder() {
return std::string("::flatbuffers::FlatBufferBuilder") +
(needs_64_bit_builder_ ? "64" : "");
}
void GenExtraIncludes() { void GenExtraIncludes() {
for (const std::string &cpp_include : opts_.cpp_includes) { for (const std::string &cpp_include : opts_.cpp_includes) {
code_ += "#include \"" + cpp_include + "\""; code_ += "#include \"" + cpp_include + "\"";
@@ -344,10 +377,8 @@ class CppGenerator : public BaseGenerator {
code_ += "#pragma clang system_header\n\n"; code_ += "#pragma clang system_header\n\n";
} }
code_ += "#include \"flatbuffers/flatbuffers.h\""; code_ += "#include <cstddef>";
code_ += ""; code_ += "#include <cstdint>";
GenFlatbuffersVersionCheck();
code_ += "";
SetNameSpace(struct_def.defined_namespace); SetNameSpace(struct_def.defined_namespace);
auto name = Name(struct_def); auto name = Name(struct_def);
@@ -396,6 +427,9 @@ class CppGenerator : public BaseGenerator {
// Iterate through all definitions we haven't generate code for (enums, // Iterate through all definitions we haven't generate code for (enums,
// structs, and tables) and output them to a single file. // structs, and tables) and output them to a single file.
bool generate() { bool generate() {
// Check if we require a 64-bit flatbuffer builder.
MarkIf64BitBuilderIsNeeded();
code_.Clear(); code_.Clear();
code_ += "// " + std::string(FlatBuffersGeneratedWarning()) + "\n\n"; code_ += "// " + std::string(FlatBuffersGeneratedWarning()) + "\n\n";
@@ -530,6 +564,8 @@ class CppGenerator : public BaseGenerator {
code_.SetValue("STRUCT_NAME", name); code_.SetValue("STRUCT_NAME", name);
code_.SetValue("CPP_NAME", cpp_name); code_.SetValue("CPP_NAME", cpp_name);
code_.SetValue("NULLABLE_EXT", NullableExtension()); code_.SetValue("NULLABLE_EXT", NullableExtension());
code_.SetValue(
"SIZE_T", needs_64_bit_builder_ ? ",::flatbuffers::uoffset64_t" : "");
// The root datatype accessor: // The root datatype accessor:
code_ += "inline \\"; code_ += "inline \\";
@@ -546,7 +582,8 @@ class CppGenerator : public BaseGenerator {
"*{{NULLABLE_EXT}}GetSizePrefixed{{STRUCT_NAME}}(const void " "*{{NULLABLE_EXT}}GetSizePrefixed{{STRUCT_NAME}}(const void "
"*buf) {"; "*buf) {";
code_ += code_ +=
" return ::flatbuffers::GetSizePrefixedRoot<{{CPP_NAME}}>(buf);"; " return "
"::flatbuffers::GetSizePrefixedRoot<{{CPP_NAME}}{{SIZE_T}}>(buf);";
code_ += "}"; code_ += "}";
code_ += ""; code_ += "";
@@ -565,7 +602,8 @@ class CppGenerator : public BaseGenerator {
"*buf) {"; "*buf) {";
code_ += code_ +=
" return " " return "
"::flatbuffers::GetMutableSizePrefixedRoot<{{CPP_NAME}}>(buf);"; "::flatbuffers::GetMutableSizePrefixedRoot<{{CPP_NAME}}{{SIZE_T}}>("
"buf);";
code_ += "}"; code_ += "}";
code_ += ""; code_ += "";
} }
@@ -612,7 +650,8 @@ class CppGenerator : public BaseGenerator {
code_ += "inline bool VerifySizePrefixed{{STRUCT_NAME}}Buffer("; code_ += "inline bool VerifySizePrefixed{{STRUCT_NAME}}Buffer(";
code_ += " ::flatbuffers::Verifier &verifier) {"; code_ += " ::flatbuffers::Verifier &verifier) {";
code_ += code_ +=
" return verifier.VerifySizePrefixedBuffer<{{CPP_NAME}}>({{ID}});"; " return "
"verifier.VerifySizePrefixedBuffer<{{CPP_NAME}}{{SIZE_T}}>({{ID}});";
code_ += "}"; code_ += "}";
code_ += ""; code_ += "";
@@ -626,7 +665,7 @@ class CppGenerator : public BaseGenerator {
// Finish a buffer with a given root object: // Finish a buffer with a given root object:
code_ += "inline void Finish{{STRUCT_NAME}}Buffer("; code_ += "inline void Finish{{STRUCT_NAME}}Buffer(";
code_ += " ::flatbuffers::FlatBufferBuilder &fbb,"; code_ += " " + GetBuilder() + " &fbb,";
code_ += " ::flatbuffers::Offset<{{CPP_NAME}}> root) {"; code_ += " ::flatbuffers::Offset<{{CPP_NAME}}> root) {";
if (parser_.file_identifier_.length()) if (parser_.file_identifier_.length())
code_ += " fbb.Finish(root, {{STRUCT_NAME}}Identifier());"; code_ += " fbb.Finish(root, {{STRUCT_NAME}}Identifier());";
@@ -636,7 +675,7 @@ class CppGenerator : public BaseGenerator {
code_ += ""; code_ += "";
code_ += "inline void FinishSizePrefixed{{STRUCT_NAME}}Buffer("; code_ += "inline void FinishSizePrefixed{{STRUCT_NAME}}Buffer(";
code_ += " ::flatbuffers::FlatBufferBuilder &fbb,"; code_ += " " + GetBuilder() + " &fbb,";
code_ += " ::flatbuffers::Offset<{{CPP_NAME}}> root) {"; code_ += " ::flatbuffers::Offset<{{CPP_NAME}}> root) {";
if (parser_.file_identifier_.length()) if (parser_.file_identifier_.length())
code_ += " fbb.FinishSizePrefixed(root, {{STRUCT_NAME}}Identifier());"; code_ += " fbb.FinishSizePrefixed(root, {{STRUCT_NAME}}Identifier());";
@@ -696,6 +735,7 @@ class CppGenerator : public BaseGenerator {
const IDLOptionsCpp opts_; const IDLOptionsCpp opts_;
const TypedFloatConstantGenerator float_const_gen_; const TypedFloatConstantGenerator float_const_gen_;
bool needs_64_bit_builder_ = false;
const Namespace *CurrentNameSpace() const { return cur_name_space_; } const Namespace *CurrentNameSpace() const { return cur_name_space_; }
@@ -737,7 +777,12 @@ class CppGenerator : public BaseGenerator {
if (type.enum_def) return WrapInNameSpace(*type.enum_def); if (type.enum_def) return WrapInNameSpace(*type.enum_def);
if (type.base_type == BASE_TYPE_BOOL) return "bool"; if (type.base_type == BASE_TYPE_BOOL) return "bool";
} }
return StringOf(type.base_type); // Get real underlying type for union type
auto base_type = type.base_type;
if (type.base_type == BASE_TYPE_UTYPE && type.enum_def != nullptr) {
base_type = type.enum_def->underlying_type.base_type;
}
return StringOf(base_type);
} }
// Return a C++ pointer type, specialized to the actual struct/table types, // Return a C++ pointer type, specialized to the actual struct/table types,
@@ -747,10 +792,14 @@ class CppGenerator : public BaseGenerator {
case BASE_TYPE_STRING: { case BASE_TYPE_STRING: {
return "::flatbuffers::String"; return "::flatbuffers::String";
} }
case BASE_TYPE_VECTOR64:
case BASE_TYPE_VECTOR: { case BASE_TYPE_VECTOR: {
const auto type_name = GenTypeWire( const auto type_name = GenTypeWire(
type.VectorType(), "", VectorElementUserFacing(type.VectorType())); type.VectorType(), "", VectorElementUserFacing(type.VectorType()));
return "::flatbuffers::Vector<" + type_name + ">"; return "::flatbuffers::Vector" +
std::string((type.base_type == BASE_TYPE_VECTOR64) ? "64<"
: "<") +
type_name + ">";
} }
case BASE_TYPE_STRUCT: { case BASE_TYPE_STRUCT: {
return WrapInNameSpace(*type.struct_def); return WrapInNameSpace(*type.struct_def);
@@ -766,13 +815,15 @@ class CppGenerator : public BaseGenerator {
// Return a C++ type for any type (scalar/pointer) specifically for // Return a C++ type for any type (scalar/pointer) specifically for
// building a flatbuffer. // building a flatbuffer.
std::string GenTypeWire(const Type &type, const char *postfix, std::string GenTypeWire(const Type &type, const char *postfix,
bool user_facing_type) const { bool user_facing_type,
bool _64_bit_offset = false) const {
if (IsScalar(type.base_type)) { if (IsScalar(type.base_type)) {
return GenTypeBasic(type, user_facing_type) + postfix; return GenTypeBasic(type, user_facing_type) + postfix;
} else if (IsStruct(type)) { } else if (IsStruct(type)) {
return "const " + GenTypePointer(type) + " *"; return "const " + GenTypePointer(type) + " *";
} else { } else {
return "::flatbuffers::Offset<" + GenTypePointer(type) + ">" + postfix; return "::flatbuffers::Offset" + std::string(_64_bit_offset ? "64" : "") +
"<" + GenTypePointer(type) + ">" + postfix;
} }
} }
@@ -858,6 +909,7 @@ class CppGenerator : public BaseGenerator {
case BASE_TYPE_STRING: { case BASE_TYPE_STRING: {
return NativeString(&field); return NativeString(&field);
} }
case BASE_TYPE_VECTOR64:
case BASE_TYPE_VECTOR: { case BASE_TYPE_VECTOR: {
const auto type_name = GenTypeNative(type.VectorType(), true, field); const auto type_name = GenTypeNative(type.VectorType(), true, field);
if (type.struct_def && if (type.struct_def &&
@@ -866,8 +918,9 @@ class CppGenerator : public BaseGenerator {
type.struct_def->attributes.Lookup("native_custom_alloc"); type.struct_def->attributes.Lookup("native_custom_alloc");
return "std::vector<" + type_name + "," + return "std::vector<" + type_name + "," +
native_custom_alloc->constant + "<" + type_name + ">>"; native_custom_alloc->constant + "<" + type_name + ">>";
} else } else {
return "std::vector<" + type_name + ">"; return "std::vector<" + type_name + ">";
}
} }
case BASE_TYPE_STRUCT: { case BASE_TYPE_STRUCT: {
auto type_name = WrapInNameSpace(*type.struct_def); auto type_name = WrapInNameSpace(*type.struct_def);
@@ -998,7 +1051,7 @@ class CppGenerator : public BaseGenerator {
std::string UnionVectorVerifySignature(const EnumDef &enum_def) { std::string UnionVectorVerifySignature(const EnumDef &enum_def) {
const std::string name = Name(enum_def); const std::string name = Name(enum_def);
const std::string &type = opts_.scoped_enums ? name : "uint8_t"; const std::string &type = opts_.scoped_enums ? name : GenTypeBasic(enum_def.underlying_type, false);
return "bool Verify" + name + "Vector" + return "bool Verify" + name + "Vector" +
"(::flatbuffers::Verifier &verifier, " + "(::flatbuffers::Verifier &verifier, " +
"const ::flatbuffers::Vector<::flatbuffers::Offset<void>> " "const ::flatbuffers::Vector<::flatbuffers::Offset<void>> "
@@ -1015,8 +1068,8 @@ class CppGenerator : public BaseGenerator {
std::string UnionPackSignature(const EnumDef &enum_def, bool inclass) { std::string UnionPackSignature(const EnumDef &enum_def, bool inclass) {
return "::flatbuffers::Offset<void> " + return "::flatbuffers::Offset<void> " +
(inclass ? "" : Name(enum_def) + "Union::") + (inclass ? "" : Name(enum_def) + "Union::") + "Pack(" +
"Pack(::flatbuffers::FlatBufferBuilder &_fbb, " + GetBuilder() + " &_fbb, " +
"const ::flatbuffers::rehasher_function_t *_rehasher" + "const ::flatbuffers::rehasher_function_t *_rehasher" +
(inclass ? " = nullptr" : "") + ") const"; (inclass ? " = nullptr" : "") + ") const";
} }
@@ -1024,8 +1077,7 @@ class CppGenerator : public BaseGenerator {
std::string TableCreateSignature(const StructDef &struct_def, bool predecl, std::string TableCreateSignature(const StructDef &struct_def, bool predecl,
const IDLOptions &opts) { const IDLOptions &opts) {
return "::flatbuffers::Offset<" + Name(struct_def) + "> Create" + return "::flatbuffers::Offset<" + Name(struct_def) + "> Create" +
Name(struct_def) + Name(struct_def) + "(" + GetBuilder() + " &_fbb, const " +
"(::flatbuffers::FlatBufferBuilder &_fbb, const " +
NativeName(Name(struct_def), &struct_def, opts) + NativeName(Name(struct_def), &struct_def, opts) +
" *_o, const ::flatbuffers::rehasher_function_t *_rehasher" + " *_o, const ::flatbuffers::rehasher_function_t *_rehasher" +
(predecl ? " = nullptr" : "") + ")"; (predecl ? " = nullptr" : "") + ")";
@@ -1035,7 +1087,7 @@ class CppGenerator : public BaseGenerator {
const IDLOptions &opts) { const IDLOptions &opts) {
return std::string(inclass ? "static " : "") + "::flatbuffers::Offset<" + return std::string(inclass ? "static " : "") + "::flatbuffers::Offset<" +
Name(struct_def) + "> " + (inclass ? "" : Name(struct_def) + "::") + Name(struct_def) + "> " + (inclass ? "" : Name(struct_def) + "::") +
"Pack(::flatbuffers::FlatBufferBuilder &_fbb, " + "const " + "Pack(" + GetBuilder() + " &_fbb, " + "const " +
NativeName(Name(struct_def), &struct_def, opts) + "* _o, " + NativeName(Name(struct_def), &struct_def, opts) + "* _o, " +
"const ::flatbuffers::rehasher_function_t *_rehasher" + "const ::flatbuffers::rehasher_function_t *_rehasher" +
(inclass ? " = nullptr" : "") + ")"; (inclass ? " = nullptr" : "") + ")";
@@ -1791,7 +1843,8 @@ class CppGenerator : public BaseGenerator {
if (IsStruct(vtype)) { if (IsStruct(vtype)) {
type = WrapInNameSpace(*vtype.struct_def); type = WrapInNameSpace(*vtype.struct_def);
} else { } else {
type = GenTypeWire(vtype, "", VectorElementUserFacing(vtype)); type = GenTypeWire(vtype, "", VectorElementUserFacing(vtype),
field.offset64);
} }
if (TypeHasKey(vtype)) { if (TypeHasKey(vtype)) {
code_.SetValue("PARAM_TYPE", "std::vector<" + type + "> *"); code_.SetValue("PARAM_TYPE", "std::vector<" + type + "> *");
@@ -1805,7 +1858,8 @@ class CppGenerator : public BaseGenerator {
if (field.IsScalarOptional()) if (field.IsScalarOptional())
code_.SetValue("PARAM_TYPE", GenOptionalDecl(type) + " "); code_.SetValue("PARAM_TYPE", GenOptionalDecl(type) + " ");
else else
code_.SetValue("PARAM_TYPE", GenTypeWire(type, " ", true)); code_.SetValue("PARAM_TYPE",
GenTypeWire(type, " ", true, field.offset64));
} }
code_ += "{{PRE}}{{PARAM_TYPE}}{{PARAM_NAME}} = {{PARAM_VALUE}}\\"; code_ += "{{PRE}}{{PARAM_TYPE}}{{PARAM_NAME}} = {{PARAM_VALUE}}\\";
} }
@@ -1814,7 +1868,7 @@ class CppGenerator : public BaseGenerator {
void GenMember(const FieldDef &field) { void GenMember(const FieldDef &field) {
if (!field.deprecated && // Deprecated fields won't be accessible. if (!field.deprecated && // Deprecated fields won't be accessible.
field.value.type.base_type != BASE_TYPE_UTYPE && field.value.type.base_type != BASE_TYPE_UTYPE &&
(field.value.type.base_type != BASE_TYPE_VECTOR || (!IsVector(field.value.type) ||
field.value.type.element != BASE_TYPE_UTYPE)) { field.value.type.element != BASE_TYPE_UTYPE)) {
auto type = GenTypeNative(field.value.type, false, field); auto type = GenTypeNative(field.value.type, false, field);
auto cpp_type = field.attributes.Lookup("cpp_type"); auto cpp_type = field.attributes.Lookup("cpp_type");
@@ -1918,7 +1972,7 @@ class CppGenerator : public BaseGenerator {
Name(field) + "(" + native_default->constant + ")"; Name(field) + "(" + native_default->constant + ")";
} }
} }
} else if (cpp_type && field.value.type.base_type != BASE_TYPE_VECTOR) { } else if (cpp_type && !IsVector(field.value.type)) {
if (!initializer_list.empty()) { initializer_list += ",\n "; } if (!initializer_list.empty()) { initializer_list += ",\n "; }
initializer_list += Name(field) + "(0)"; initializer_list += Name(field) + "(0)";
} }
@@ -2063,7 +2117,7 @@ class CppGenerator : public BaseGenerator {
const auto rhs_accessor = "rhs." + accessor; const auto rhs_accessor = "rhs." + accessor;
if (!field.deprecated && // Deprecated fields won't be accessible. if (!field.deprecated && // Deprecated fields won't be accessible.
field.value.type.base_type != BASE_TYPE_UTYPE && field.value.type.base_type != BASE_TYPE_UTYPE &&
(field.value.type.base_type != BASE_TYPE_VECTOR || (!IsVector(field.value.type) ||
field.value.type.element != BASE_TYPE_UTYPE)) { field.value.type.element != BASE_TYPE_UTYPE)) {
if (!compare_op.empty()) { compare_op += " &&\n "; } if (!compare_op.empty()) { compare_op += " &&\n "; }
if (struct_def.fixed || field.native_inline || if (struct_def.fixed || field.native_inline ||
@@ -2195,7 +2249,10 @@ class CppGenerator : public BaseGenerator {
"{{PRE}}VerifyField{{REQUIRED}}<{{SIZE}}>(verifier, " "{{PRE}}VerifyField{{REQUIRED}}<{{SIZE}}>(verifier, "
"{{OFFSET}}, {{ALIGN}})\\"; "{{OFFSET}}, {{ALIGN}})\\";
} else { } else {
code_ += "{{PRE}}VerifyOffset{{REQUIRED}}(verifier, {{OFFSET}})\\"; code_.SetValue("OFFSET_SIZE", field.offset64 ? "64" : "");
code_ +=
"{{PRE}}VerifyOffset{{OFFSET_SIZE}}{{REQUIRED}}(verifier, "
"{{OFFSET}})\\";
} }
switch (field.value.type.base_type) { switch (field.value.type.base_type) {
@@ -2217,6 +2274,7 @@ class CppGenerator : public BaseGenerator {
code_ += "{{PRE}}verifier.VerifyString({{NAME}}())\\"; code_ += "{{PRE}}verifier.VerifyString({{NAME}}())\\";
break; break;
} }
case BASE_TYPE_VECTOR64:
case BASE_TYPE_VECTOR: { case BASE_TYPE_VECTOR: {
code_ += "{{PRE}}verifier.VerifyVector({{NAME}}())\\"; code_ += "{{PRE}}verifier.VerifyVector({{NAME}}())\\";
@@ -2468,12 +2526,18 @@ class CppGenerator : public BaseGenerator {
if (!field.IsScalarOptional()) { if (!field.IsScalarOptional()) {
const bool is_scalar = IsScalar(type.base_type); const bool is_scalar = IsScalar(type.base_type);
std::string accessor; std::string accessor;
if (is_scalar) std::string offset_size = "";
if (is_scalar) {
accessor = "GetField<"; accessor = "GetField<";
else if (IsStruct(type)) } else if (IsStruct(type)) {
accessor = "GetStruct<"; accessor = "GetStruct<";
else } else {
accessor = "GetPointer<"; if (field.offset64) {
accessor = "GetPointer64<";
} else {
accessor = "GetPointer<";
}
}
auto offset_type = GenTypeGet(type, "", "const ", " *", false); auto offset_type = GenTypeGet(type, "", "const ", " *", false);
auto call = accessor + offset_type + ">(" + offset_str; auto call = accessor + offset_type + ">(" + offset_str;
// Default value as second arg for non-pointer types. // Default value as second arg for non-pointer types.
@@ -2633,7 +2697,7 @@ class CppGenerator : public BaseGenerator {
auto offset_str = GenFieldOffsetName(field); auto offset_str = GenFieldOffsetName(field);
if (is_scalar) { if (is_scalar) {
const auto wire_type = GenTypeWire(type, "", false); const auto wire_type = GenTypeWire(type, "", false, field.offset64);
code_.SetValue("SET_FN", "SetField<" + wire_type + ">"); code_.SetValue("SET_FN", "SetField<" + wire_type + ">");
code_.SetValue("OFFSET_NAME", offset_str); code_.SetValue("OFFSET_NAME", offset_str);
code_.SetValue("FIELD_TYPE", GenTypeBasic(type, true)); code_.SetValue("FIELD_TYPE", GenTypeBasic(type, true));
@@ -2665,7 +2729,11 @@ class CppGenerator : public BaseGenerator {
} else { } else {
auto postptr = " *" + NullableExtension(); auto postptr = " *" + NullableExtension();
auto wire_type = GenTypeGet(type, " ", "", postptr.c_str(), true); auto wire_type = GenTypeGet(type, " ", "", postptr.c_str(), true);
std::string accessor = IsStruct(type) ? "GetStruct<" : "GetPointer<"; const std::string accessor = [&]() {
if (IsStruct(type)) { return "GetStruct<"; }
if (field.offset64) { return "GetPointer64<"; }
return "GetPointer<";
}();
auto underlying = accessor + wire_type + ">(" + offset_str + ")"; auto underlying = accessor + wire_type + ">(" + offset_str + ")";
code_.SetValue("FIELD_TYPE", wire_type); code_.SetValue("FIELD_TYPE", wire_type);
code_.SetValue("FIELD_VALUE", GenUnderlyingCast(field, true, underlying)); code_.SetValue("FIELD_VALUE", GenUnderlyingCast(field, true, underlying));
@@ -2859,9 +2927,9 @@ class CppGenerator : public BaseGenerator {
// Generate code to do force_align for the vector. // Generate code to do force_align for the vector.
if (align > 1) { if (align > 1) {
const auto vtype = field.value.type.VectorType(); const auto vtype = field.value.type.VectorType();
const std::string &type = IsStruct(vtype) const std::string &type =
? WrapInNameSpace(*vtype.struct_def) IsStruct(vtype) ? WrapInNameSpace(*vtype.struct_def)
: GenTypeWire(vtype, "", false); : GenTypeWire(vtype, "", false, field.offset64);
return "_fbb.ForceVectorAlignment(" + field_size + ", sizeof(" + type + return "_fbb.ForceVectorAlignment(" + field_size + ", sizeof(" + type +
"), " + std::to_string(static_cast<long long>(align)) + ");"; "), " + std::to_string(static_cast<long long>(align)) + ");";
} }
@@ -2874,7 +2942,7 @@ class CppGenerator : public BaseGenerator {
// Generate a builder struct: // Generate a builder struct:
code_ += "struct {{STRUCT_NAME}}Builder {"; code_ += "struct {{STRUCT_NAME}}Builder {";
code_ += " typedef {{STRUCT_NAME}} Table;"; code_ += " typedef {{STRUCT_NAME}} Table;";
code_ += " ::flatbuffers::FlatBufferBuilder &fbb_;"; code_ += " " + GetBuilder() + " &fbb_;";
code_ += " ::flatbuffers::uoffset_t start_;"; code_ += " ::flatbuffers::uoffset_t start_;";
bool has_string_or_vector_fields = false; bool has_string_or_vector_fields = false;
@@ -2897,12 +2965,14 @@ class CppGenerator : public BaseGenerator {
// fbb_.AddElement<type>(offset, name, default); // fbb_.AddElement<type>(offset, name, default);
// } // }
code_.SetValue("FIELD_NAME", Name(field)); code_.SetValue("FIELD_NAME", Name(field));
code_.SetValue("FIELD_TYPE", GenTypeWire(field.value.type, " ", true)); code_.SetValue("FIELD_TYPE",
GenTypeWire(field.value.type, " ", true, field.offset64));
code_.SetValue("ADD_OFFSET", Name(struct_def) + "::" + offset); code_.SetValue("ADD_OFFSET", Name(struct_def) + "::" + offset);
code_.SetValue("ADD_NAME", name); code_.SetValue("ADD_NAME", name);
code_.SetValue("ADD_VALUE", value); code_.SetValue("ADD_VALUE", value);
if (is_scalar) { if (is_scalar) {
const auto type = GenTypeWire(field.value.type, "", false); const auto type =
GenTypeWire(field.value.type, "", false, field.offset64);
code_.SetValue("ADD_FN", "AddElement<" + type + ">"); code_.SetValue("ADD_FN", "AddElement<" + type + ">");
} else if (IsStruct(field.value.type)) { } else if (IsStruct(field.value.type)) {
code_.SetValue("ADD_FN", "AddStruct"); code_.SetValue("ADD_FN", "AddStruct");
@@ -2921,9 +2991,9 @@ class CppGenerator : public BaseGenerator {
} }
// Builder constructor // Builder constructor
code_ += code_ += " explicit {{STRUCT_NAME}}Builder(" + GetBuilder() +
" explicit {{STRUCT_NAME}}Builder(::flatbuffers::FlatBufferBuilder " " "
"&_fbb)"; "&_fbb)";
code_ += " : fbb_(_fbb) {"; code_ += " : fbb_(_fbb) {";
code_ += " start_ = fbb_.StartTable();"; code_ += " start_ = fbb_.StartTable();";
code_ += " }"; code_ += " }";
@@ -2950,7 +3020,7 @@ class CppGenerator : public BaseGenerator {
code_ += code_ +=
"inline ::flatbuffers::Offset<{{STRUCT_NAME}}> " "inline ::flatbuffers::Offset<{{STRUCT_NAME}}> "
"Create{{STRUCT_NAME}}("; "Create{{STRUCT_NAME}}(";
code_ += " ::flatbuffers::FlatBufferBuilder &_fbb\\"; code_ += " " + GetBuilder() + " &_fbb\\";
for (const auto &field : struct_def.fields.vec) { for (const auto &field : struct_def.fields.vec) {
if (!field->deprecated) { GenParam(*field, false, ",\n "); } if (!field->deprecated) { GenParam(*field, false, ",\n "); }
} }
@@ -2988,7 +3058,7 @@ class CppGenerator : public BaseGenerator {
code_ += code_ +=
"inline ::flatbuffers::Offset<{{STRUCT_NAME}}> " "inline ::flatbuffers::Offset<{{STRUCT_NAME}}> "
"Create{{STRUCT_NAME}}Direct("; "Create{{STRUCT_NAME}}Direct(";
code_ += " ::flatbuffers::FlatBufferBuilder &_fbb\\"; code_ += " " + GetBuilder() + " &_fbb\\";
for (const auto &field : struct_def.fields.vec) { for (const auto &field : struct_def.fields.vec) {
if (!field->deprecated) { GenParam(*field, true, ",\n "); } if (!field->deprecated) { GenParam(*field, true, ",\n "); }
} }
@@ -2997,54 +3067,85 @@ class CppGenerator : public BaseGenerator {
struct_def.defined_namespace->GetFullyQualifiedName("Create"); struct_def.defined_namespace->GetFullyQualifiedName("Create");
code_.SetValue("CREATE_NAME", TranslateNameSpace(qualified_create_name)); code_.SetValue("CREATE_NAME", TranslateNameSpace(qualified_create_name));
code_ += ") {"; code_ += ") {";
for (const auto &field : struct_def.fields.vec) { // Offset64 bit fields need to be added to the buffer first, so here we
if (!field->deprecated) { // loop over the fields in order of their offset size, followed by their
code_.SetValue("FIELD_NAME", Name(*field)); // definition order. Otherwise the emitted code might add a Offset
if (IsString(field->value.type)) { // followed by an Offset64 which would trigger an assertion.
if (!field->shared) {
code_.SetValue("CREATE_STRING", "CreateString"); // TODO(derekbailey): maybe optimize for the case where there is no
} else { // 64offsets in the whole schema?
code_.SetValue("CREATE_STRING", "CreateSharedString"); ForAllFieldsOrderedByOffset(struct_def, [&](const FieldDef *field) {
} if (field->deprecated) { return; }
code_ += code_.SetValue("FIELD_NAME", Name(*field));
" auto {{FIELD_NAME}}__ = {{FIELD_NAME}} ? " if (IsString(field->value.type)) {
"_fbb.{{CREATE_STRING}}({{FIELD_NAME}}) : 0;"; if (!field->shared) {
} else if (IsVector(field->value.type)) { code_.SetValue(
const std::string force_align_code = "CREATE_STRING",
GenVectorForceAlign(*field, Name(*field) + "->size()"); "CreateString" + std::string(field->offset64
if (!force_align_code.empty()) { ? "<::flatbuffers::Offset64>"
code_ += " if ({{FIELD_NAME}}) { " + force_align_code + " }"; : ""));
} } else {
code_ += " auto {{FIELD_NAME}}__ = {{FIELD_NAME}} ? \\"; code_.SetValue("CREATE_STRING", "CreateSharedString");
const auto vtype = field->value.type.VectorType();
const auto has_key = TypeHasKey(vtype);
if (IsStruct(vtype)) {
const auto type = WrapInNameSpace(*vtype.struct_def);
code_ += (has_key ? "_fbb.CreateVectorOfSortedStructs<"
: "_fbb.CreateVectorOfStructs<") +
type + ">\\";
} else if (has_key) {
const auto type = WrapInNameSpace(*vtype.struct_def);
code_ += "_fbb.CreateVectorOfSortedTables<" + type + ">\\";
} else {
const auto type =
GenTypeWire(vtype, "", VectorElementUserFacing(vtype));
code_ += "_fbb.CreateVector<" + type + ">\\";
}
code_ +=
has_key ? "({{FIELD_NAME}}) : 0;" : "(*{{FIELD_NAME}}) : 0;";
} }
code_ +=
" auto {{FIELD_NAME}}__ = {{FIELD_NAME}} ? "
"_fbb.{{CREATE_STRING}}({{FIELD_NAME}}) : 0;";
} else if (IsVector(field->value.type)) {
const std::string force_align_code =
GenVectorForceAlign(*field, Name(*field) + "->size()");
if (!force_align_code.empty()) {
code_ += " if ({{FIELD_NAME}}) { " + force_align_code + " }";
}
code_ += " auto {{FIELD_NAME}}__ = {{FIELD_NAME}} ? \\";
const auto vtype = field->value.type.VectorType();
const auto has_key = TypeHasKey(vtype);
if (IsStruct(vtype)) {
const std::string type = WrapInNameSpace(*vtype.struct_def);
if (has_key) {
code_ += "_fbb.CreateVectorOfSortedStructs<" + type + ">\\";
} else {
// If the field uses 64-bit addressing, create a 64-bit vector.
if (field->value.type.base_type == BASE_TYPE_VECTOR64) {
code_ += "_fbb.CreateVectorOfStructs64\\";
} else {
code_ += "_fbb.CreateVectorOfStructs\\";
if (field->offset64) {
// This is normal 32-bit vector, with 64-bit addressing.
code_ += "64<::flatbuffers::Vector>\\";
} else {
code_ += "<" + type + ">\\";
}
}
}
} else if (has_key) {
const auto type = WrapInNameSpace(*vtype.struct_def);
code_ += "_fbb.CreateVectorOfSortedTables<" + type + ">\\";
} else {
const auto type = GenTypeWire(
vtype, "", VectorElementUserFacing(vtype), field->offset64);
if (field->value.type.base_type == BASE_TYPE_VECTOR64) {
code_ += "_fbb.CreateVector64\\";
} else {
// If the field uses 64-bit addressing, create a 64-bit vector.
code_.SetValue("64OFFSET", field->offset64 ? "64" : "");
code_.SetValue("TYPE",
field->offset64 ? "::flatbuffers::Vector" : type);
code_ += "_fbb.CreateVector{{64OFFSET}}<{{TYPE}}>\\";
}
}
code_ += has_key ? "({{FIELD_NAME}}) : 0;" : "(*{{FIELD_NAME}}) : 0;";
} }
} });
code_ += " return {{CREATE_NAME}}{{STRUCT_NAME}}("; code_ += " return {{CREATE_NAME}}{{STRUCT_NAME}}(";
code_ += " _fbb\\"; code_ += " _fbb\\";
for (const auto &field : struct_def.fields.vec) { for (const auto &field : struct_def.fields.vec) {
if (!field->deprecated) { if (field->deprecated) { continue; }
code_.SetValue("FIELD_NAME", Name(*field)); code_.SetValue("FIELD_NAME", Name(*field));
code_ += ",\n {{FIELD_NAME}}\\"; code_ += ",\n {{FIELD_NAME}}\\";
if (IsString(field->value.type) || IsVector(field->value.type)) { if (IsString(field->value.type) || IsVector(field->value.type)) {
code_ += "__\\"; code_ += "__\\";
}
} }
} }
code_ += ");"; code_ += ");";
@@ -3115,6 +3216,7 @@ class CppGenerator : public BaseGenerator {
const FieldDef *union_field) { const FieldDef *union_field) {
std::string code; std::string code;
switch (field.value.type.base_type) { switch (field.value.type.base_type) {
case BASE_TYPE_VECTOR64:
case BASE_TYPE_VECTOR: { case BASE_TYPE_VECTOR: {
auto name = Name(field); auto name = Name(field);
if (field.value.type.element == BASE_TYPE_UTYPE) { if (field.value.type.element == BASE_TYPE_UTYPE) {
@@ -3151,8 +3253,11 @@ class CppGenerator : public BaseGenerator {
? ".type" ? ".type"
: (field.value.type.element == BASE_TYPE_UNION ? ".value" : (field.value.type.element == BASE_TYPE_UNION ? ".value"
: ""); : "");
if (field.value.type.base_type == BASE_TYPE_VECTOR64) {
code += "for (::flatbuffers::uoffset_t _i = 0;"; code += "for (::flatbuffers::uoffset64_t _i = 0;";
} else {
code += "for (::flatbuffers::uoffset_t _i = 0;";
}
code += " _i < _e->size(); _i++) { "; code += " _i < _e->size(); _i++) { ";
auto cpp_type = field.attributes.Lookup("cpp_type"); auto cpp_type = field.attributes.Lookup("cpp_type");
if (cpp_type) { if (cpp_type) {
@@ -3265,8 +3370,7 @@ class CppGenerator : public BaseGenerator {
} else { } else {
value += Name(field); value += Name(field);
} }
if (field.value.type.base_type != BASE_TYPE_VECTOR && if (!IsVector(field.value.type) && field.attributes.Lookup("cpp_type")) {
field.attributes.Lookup("cpp_type")) {
auto type = GenTypeBasic(field.value.type, false); auto type = GenTypeBasic(field.value.type, false);
value = value =
"_rehasher ? " "_rehasher ? "
@@ -3282,7 +3386,10 @@ class CppGenerator : public BaseGenerator {
// _fbb.CreateSharedString(_o->field) // _fbb.CreateSharedString(_o->field)
case BASE_TYPE_STRING: { case BASE_TYPE_STRING: {
if (!field.shared) { if (!field.shared) {
code += "_fbb.CreateString("; code +=
"_fbb.CreateString" +
std::string(field.offset64 ? "<::flatbuffers::Offset64>" : "") +
"(";
} else { } else {
code += "_fbb.CreateSharedString("; code += "_fbb.CreateSharedString(";
} }
@@ -3309,6 +3416,7 @@ class CppGenerator : public BaseGenerator {
// _fbb.CreateVector<Offset<T>>(_o->field.size() [&](size_t i) { // _fbb.CreateVector<Offset<T>>(_o->field.size() [&](size_t i) {
// return CreateT(_fbb, _o->Get(i), rehasher); // return CreateT(_fbb, _o->Get(i), rehasher);
// }); // });
case BASE_TYPE_VECTOR64:
case BASE_TYPE_VECTOR: { case BASE_TYPE_VECTOR: {
auto vector_type = field.value.type.VectorType(); auto vector_type = field.value.type.VectorType();
switch (vector_type.base_type) { switch (vector_type.base_type) {
@@ -3347,7 +3455,16 @@ class CppGenerator : public BaseGenerator {
} }
code += ")"; code += ")";
} else { } else {
code += "_fbb.CreateVectorOfStructs"; // If the field uses 64-bit addressing, create a 64-bit vector.
if (field.value.type.base_type == BASE_TYPE_VECTOR64) {
code += "_fbb.CreateVectorOfStructs64";
} else {
code += "_fbb.CreateVectorOfStructs";
if (field.offset64) {
// This is normal 32-bit vector, with 64-bit addressing.
code += "64<::flatbuffers::Vector>";
}
}
code += "(" + value + ")"; code += "(" + value + ")";
} }
} else { } else {
@@ -3382,12 +3499,13 @@ class CppGenerator : public BaseGenerator {
} }
case BASE_TYPE_UTYPE: { case BASE_TYPE_UTYPE: {
value = StripUnionType(value); value = StripUnionType(value);
auto underlying_type = GenTypeBasic(vector_type, false);
const std::string &type = opts_.scoped_enums const std::string &type = opts_.scoped_enums
? Name(*field.value.type.enum_def) ? Name(*field.value.type.enum_def)
: "uint8_t"; : underlying_type;
auto enum_value = "__va->_" + value + "[i].type"; auto enum_value = "__va->_" + value + "[i].type";
if (!opts_.scoped_enums) if (!opts_.scoped_enums)
enum_value = "static_cast<uint8_t>(" + enum_value + ")"; enum_value = "static_cast<" + underlying_type + ">(" + enum_value + ")";
code += "_fbb.CreateVector<" + type + ">(" + value + code += "_fbb.CreateVector<" + type + ">(" + value +
".size(), [](size_t i, _VectorArgs *__va) { return " + ".size(), [](size_t i, _VectorArgs *__va) { return " +
@@ -3413,7 +3531,17 @@ class CppGenerator : public BaseGenerator {
code += "(__va->_" + value + "[i]" + GenPtrGet(field) + ")) : 0"; code += "(__va->_" + value + "[i]" + GenPtrGet(field) + ")) : 0";
code += "; }, &_va )"; code += "; }, &_va )";
} else { } else {
code += "_fbb.CreateVector(" + value + ")"; // If the field uses 64-bit addressing, create a 64-bit vector.
if (field.value.type.base_type == BASE_TYPE_VECTOR64) {
code += "_fbb.CreateVector64(" + value + ")";
} else {
code += "_fbb.CreateVector";
if (field.offset64) {
// This is normal 32-bit vector, with 64-bit addressing.
code += "64<::flatbuffers::Vector>";
}
code += "(" + value + ")";
}
} }
break; break;
} }
@@ -3540,7 +3668,9 @@ class CppGenerator : public BaseGenerator {
code_ += code_ +=
" struct _VectorArgs " " struct _VectorArgs "
"{ ::flatbuffers::FlatBufferBuilder *__fbb; " "{ " +
GetBuilder() +
" *__fbb; "
"const " + "const " +
NativeName(Name(struct_def), &struct_def, opts_) + NativeName(Name(struct_def), &struct_def, opts_) +
"* __o; " "* __o; "
@@ -3940,8 +4070,8 @@ class CppGenerator : public BaseGenerator {
} // namespace cpp } // namespace cpp
bool GenerateCPP(const Parser &parser, const std::string &path, static bool GenerateCPP(const Parser &parser, const std::string &path,
const std::string &file_name) { const std::string &file_name) {
cpp::IDLOptionsCpp opts(parser.opts); cpp::IDLOptionsCpp opts(parser.opts);
// The '--cpp_std' argument could be extended (like ASAN): // The '--cpp_std' argument could be extended (like ASAN):
// Example: "flatc --cpp_std c++17:option1:option2". // Example: "flatc --cpp_std c++17:option1:option2".
@@ -3979,8 +4109,8 @@ bool GenerateCPP(const Parser &parser, const std::string &path,
return generator.generate(); return generator.generate();
} }
std::string CPPMakeRule(const Parser &parser, const std::string &path, static std::string CPPMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name) { const std::string &file_name) {
const auto filebase = StripPath(StripExtension(file_name)); const auto filebase = StripPath(StripExtension(file_name));
cpp::CppGenerator geneartor(parser, path, file_name, parser.opts); cpp::CppGenerator geneartor(parser, path, file_name, parser.opts);
const auto included_files = parser.GetIncludedFilesRecursive(file_name); const auto included_files = parser.GetIncludedFilesRecursive(file_name);
@@ -4004,9 +4134,8 @@ class CppCodeGenerator : public CodeGenerator {
// Generate code from the provided `buffer` of given `length`. The buffer is a // Generate code from the provided `buffer` of given `length`. The buffer is a
// serialized reflection.fbs. // serialized reflection.fbs.
Status GenerateCode(const uint8_t *buffer, int64_t length) override { Status GenerateCode(const uint8_t *, int64_t,
(void)buffer; const CodeGenOptions &) override {
(void)length;
return Status::NOT_IMPLEMENTED; return Status::NOT_IMPLEMENTED;
} }

View File

@@ -625,7 +625,8 @@ class CSharpGenerator : public BaseGenerator {
} }
// Get the value of a table verification function start // Get the value of a table verification function start
void GetStartOfTableVerifier(const StructDef &struct_def, std::string *code_ptr) { void GetStartOfTableVerifier(const StructDef &struct_def,
std::string *code_ptr) {
std::string &code = *code_ptr; std::string &code = *code_ptr;
code += "\n"; code += "\n";
code += "static public class " + struct_def.name + "Verify\n"; code += "static public class " + struct_def.name + "Verify\n";
@@ -645,17 +646,18 @@ class CSharpGenerator : public BaseGenerator {
} }
std::string GetNestedFlatBufferName(const FieldDef &field) { std::string GetNestedFlatBufferName(const FieldDef &field) {
std::string name; std::string name;
if (field.nested_flatbuffer) { if (field.nested_flatbuffer) {
name = NamespacedName(*field.nested_flatbuffer); name = NamespacedName(*field.nested_flatbuffer);
} else { } else {
name = ""; name = "";
} }
return name ; return name;
} }
// Generate the code to call the appropriate Verify function(s) for a field. // Generate the code to call the appropriate Verify function(s) for a field.
void GenVerifyCall(CodeWriter &code_, const FieldDef &field, const char *prefix) { void GenVerifyCall(CodeWriter &code_, const FieldDef &field,
const char *prefix) {
code_.SetValue("PRE", prefix); code_.SetValue("PRE", prefix);
code_.SetValue("NAME", ConvertCase(field.name, Case::kUpperCamel)); code_.SetValue("NAME", ConvertCase(field.name, Case::kUpperCamel));
code_.SetValue("REQUIRED", field.IsRequired() ? "Required" : ""); code_.SetValue("REQUIRED", field.IsRequired() ? "Required" : "");
@@ -667,10 +669,12 @@ class CSharpGenerator : public BaseGenerator {
if (IsScalar(field.value.type.base_type) || IsStruct(field.value.type)) { if (IsScalar(field.value.type.base_type) || IsStruct(field.value.type)) {
code_.SetValue("ALIGN", NumToString(InlineAlignment(field.value.type))); code_.SetValue("ALIGN", NumToString(InlineAlignment(field.value.type)));
code_ += code_ +=
"{{PRE}} && verifier.VerifyField(tablePos, " "{{PRE}} && verifier.VerifyField(tablePos, "
"{{OFFSET}} /*{{NAME}}*/, {{INLINESIZE}} /*{{TYPE}}*/, {{ALIGN}}, {{REQUIRED_FLAG}})"; "{{OFFSET}} /*{{NAME}}*/, {{INLINESIZE}} /*{{TYPE}}*/, {{ALIGN}}, "
"{{REQUIRED_FLAG}})";
} else { } else {
// TODO - probably code below should go to this 'else' - code_ += "{{PRE}}VerifyOffset{{REQUIRED}}(verifier, {{OFFSET}})\\"; // TODO - probably code below should go to this 'else' - code_ +=
// "{{PRE}}VerifyOffset{{REQUIRED}}(verifier, {{OFFSET}})\\";
} }
switch (field.value.type.base_type) { switch (field.value.type.base_type) {
@@ -679,37 +683,47 @@ class CSharpGenerator : public BaseGenerator {
code_.SetValue("ENUM_NAME1", field.value.type.enum_def->name); code_.SetValue("ENUM_NAME1", field.value.type.enum_def->name);
code_.SetValue("ENUM_NAME", union_name); code_.SetValue("ENUM_NAME", union_name);
code_.SetValue("SUFFIX", UnionTypeFieldSuffix()); code_.SetValue("SUFFIX", UnionTypeFieldSuffix());
// Caution: This construction assumes, that UNION type id element has been created just before union data and // Caution: This construction assumes, that UNION type id element has
// its offset precedes union. Such assumption is common in flatbuffer implementation // been created just before union data and its offset precedes union.
code_.SetValue("TYPE_ID_OFFSET", NumToString(field.value.offset - sizeof(voffset_t))); // Such assumption is common in flatbuffer implementation
code_ += "{{PRE}} && verifier.VerifyUnion(tablePos, {{TYPE_ID_OFFSET}}, " code_.SetValue("TYPE_ID_OFFSET",
"{{OFFSET}} /*{{NAME}}*/, {{ENUM_NAME}}Verify.Verify, {{REQUIRED_FLAG}})"; NumToString(field.value.offset - sizeof(voffset_t)));
code_ +=
"{{PRE}} && verifier.VerifyUnion(tablePos, "
"{{TYPE_ID_OFFSET}}, "
"{{OFFSET}} /*{{NAME}}*/, {{ENUM_NAME}}Verify.Verify, "
"{{REQUIRED_FLAG}})";
break; break;
} }
case BASE_TYPE_STRUCT: { case BASE_TYPE_STRUCT: {
if (!field.value.type.struct_def->fixed) { if (!field.value.type.struct_def->fixed) {
code_ += "{{PRE}} && verifier.VerifyTable(tablePos, " code_ +=
"{{OFFSET}} /*{{NAME}}*/, {{TYPE}}Verify.Verify, {{REQUIRED_FLAG}})"; "{{PRE}} && verifier.VerifyTable(tablePos, "
"{{OFFSET}} /*{{NAME}}*/, {{TYPE}}Verify.Verify, "
"{{REQUIRED_FLAG}})";
} }
break; break;
} }
case BASE_TYPE_STRING: { case BASE_TYPE_STRING: {
code_ += "{{PRE}} && verifier.VerifyString(tablePos, " code_ +=
"{{OFFSET}} /*{{NAME}}*/, {{REQUIRED_FLAG}})"; "{{PRE}} && verifier.VerifyString(tablePos, "
"{{OFFSET}} /*{{NAME}}*/, {{REQUIRED_FLAG}})";
break; break;
} }
case BASE_TYPE_VECTOR: { case BASE_TYPE_VECTOR: {
switch (field.value.type.element) { switch (field.value.type.element) {
case BASE_TYPE_STRING: { case BASE_TYPE_STRING: {
code_ += "{{PRE}} && verifier.VerifyVectorOfStrings(tablePos, " code_ +=
"{{OFFSET}} /*{{NAME}}*/, {{REQUIRED_FLAG}})"; "{{PRE}} && verifier.VerifyVectorOfStrings(tablePos, "
"{{OFFSET}} /*{{NAME}}*/, {{REQUIRED_FLAG}})";
break; break;
} }
case BASE_TYPE_STRUCT: { case BASE_TYPE_STRUCT: {
if (!field.value.type.struct_def->fixed) { if (!field.value.type.struct_def->fixed) {
code_ += "{{PRE}} && verifier.VerifyVectorOfTables(tablePos, " code_ +=
"{{OFFSET}} /*{{NAME}}*/, {{TYPE}}Verify.Verify, {{REQUIRED_FLAG}})"; "{{PRE}} && verifier.VerifyVectorOfTables(tablePos, "
"{{OFFSET}} /*{{NAME}}*/, {{TYPE}}Verify.Verify, "
"{{REQUIRED_FLAG}})";
} else { } else {
code_.SetValue( code_.SetValue(
"VECTOR_ELEM_INLINESIZE", "VECTOR_ELEM_INLINESIZE",
@@ -733,16 +747,22 @@ class CSharpGenerator : public BaseGenerator {
if (!nfn.empty()) { if (!nfn.empty()) {
code_.SetValue("CPP_NAME", nfn); code_.SetValue("CPP_NAME", nfn);
// FIXME: file_identifier. // FIXME: file_identifier.
code_ += "{{PRE}} && verifier.VerifyNestedBuffer(tablePos, "
"{{OFFSET}} /*{{NAME}}*/, {{CPP_NAME}}Verify.Verify, {{REQUIRED_FLAG}})";
} else if (field.flexbuffer) {
code_ += "{{PRE}} && verifier.VerifyNestedBuffer(tablePos, "
"{{OFFSET}} /*{{NAME}}*/, null, {{REQUIRED_FLAG}})";
} else {
code_.SetValue("VECTOR_ELEM_INLINESIZE", NumToString(InlineSize(field.value.type.VectorType())));
code_ += code_ +=
"{{PRE}} && verifier.VerifyVectorOfData(tablePos, " "{{PRE}} && verifier.VerifyNestedBuffer(tablePos, "
"{{OFFSET}} /*{{NAME}}*/, {{VECTOR_ELEM_INLINESIZE}} /*{{TYPE}}*/, {{REQUIRED_FLAG}})"; "{{OFFSET}} /*{{NAME}}*/, {{CPP_NAME}}Verify.Verify, "
"{{REQUIRED_FLAG}})";
} else if (field.flexbuffer) {
code_ +=
"{{PRE}} && verifier.VerifyNestedBuffer(tablePos, "
"{{OFFSET}} /*{{NAME}}*/, null, {{REQUIRED_FLAG}})";
} else {
code_.SetValue(
"VECTOR_ELEM_INLINESIZE",
NumToString(InlineSize(field.value.type.VectorType())));
code_ +=
"{{PRE}} && verifier.VerifyVectorOfData(tablePos, "
"{{OFFSET}} /*{{NAME}}*/, {{VECTOR_ELEM_INLINESIZE}} "
"/*{{TYPE}}*/, {{REQUIRED_FLAG}})";
} }
break; break;
} }
@@ -787,7 +807,7 @@ class CSharpGenerator : public BaseGenerator {
// verification - instead structure size is verified using VerifyField // verification - instead structure size is verified using VerifyField
} else { } else {
// Create table verification function // Create table verification function
GenTableVerifier(struct_def, code_ptr); GenTableVerifier(struct_def, code_ptr);
} }
} }
@@ -826,7 +846,7 @@ class CSharpGenerator : public BaseGenerator {
// Force compile time error if not using the same version runtime. // Force compile time error if not using the same version runtime.
code += " public static void ValidateVersion() {"; code += " public static void ValidateVersion() {";
code += " FlatBufferConstants."; code += " FlatBufferConstants.";
code += "FLATBUFFERS_23_5_8(); "; code += "FLATBUFFERS_23_5_26(); ";
code += "}\n"; code += "}\n";
// Generate a special accessor for the table that when used as the root // Generate a special accessor for the table that when used as the root
@@ -1602,8 +1622,7 @@ class CSharpGenerator : public BaseGenerator {
if (union_type.enum_def) { if (union_type.enum_def) {
const auto &enum_def = *union_type.enum_def; const auto &enum_def = *union_type.enum_def;
auto ret = auto ret = "\n\nstatic public class " + enum_def.name + "Verify\n";
"\n\nstatic public class " + enum_def.name + "Verify\n";
ret += "{\n"; ret += "{\n";
ret += ret +=
" static public bool Verify(Google.FlatBuffers.Verifier verifier, " " static public bool Verify(Google.FlatBuffers.Verifier verifier, "
@@ -1615,25 +1634,26 @@ class CSharpGenerator : public BaseGenerator {
ret += " switch((" + enum_def.name + ")typeId)\n"; ret += " switch((" + enum_def.name + ")typeId)\n";
ret += " {\n"; ret += " {\n";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) { for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end();
++it) {
const auto &ev = **it; const auto &ev = **it;
if (ev.IsZero()) { continue; } if (ev.IsZero()) { continue; }
ret += " case " + Name(enum_def) + "." + Name(ev) + ":\n"; ret += " case " + Name(enum_def) + "." + Name(ev) + ":\n";
if (IsString(ev.union_type)) { if (IsString(ev.union_type)) {
ret += ret += " result = verifier.VerifyUnionString(tablePos);\n";
" result = verifier.VerifyUnionString(tablePos);\n";
ret += " break;"; ret += " break;";
} else if (ev.union_type.base_type == BASE_TYPE_STRUCT) { } else if (ev.union_type.base_type == BASE_TYPE_STRUCT) {
if (! ev.union_type.struct_def->fixed) { if (!ev.union_type.struct_def->fixed) {
auto type = GenTypeGet(ev.union_type); auto type = GenTypeGet(ev.union_type);
ret += " result = " + type + "Verify.Verify(verifier, tablePos);\n"; ret += " result = " + type +
"Verify.Verify(verifier, tablePos);\n";
} else { } else {
ret += " result = verifier.VerifyUnionData(tablePos, " + ret += " result = verifier.VerifyUnionData(tablePos, " +
NumToString(InlineSize(ev.union_type)) + ", " + NumToString(InlineSize(ev.union_type)) + ", " +
NumToString(InlineAlignment(ev.union_type)) + NumToString(InlineAlignment(ev.union_type)) + ");\n";
");\n";; ;
} }
ret += " break;"; ret += " break;";
} else { } else {
@@ -1676,7 +1696,7 @@ class CSharpGenerator : public BaseGenerator {
// Type // Type
code += " public " + enum_def.name + " Type { get; set; }\n"; code += " public " + enum_def.name + " Type { get; set; }\n";
// Value // Value
code += " public object " + class_member + " { get; set; }\n"; code += " public object " + class_member + " { get; set; }\n";
code += "\n"; code += "\n";
// Constructor // Constructor
code += " public " + union_name + "() {\n"; code += " public " + union_name + "() {\n";
@@ -1773,7 +1793,7 @@ class CSharpGenerator : public BaseGenerator {
" _o, " " _o, "
"Newtonsoft.Json.JsonSerializer serializer) {\n"; "Newtonsoft.Json.JsonSerializer serializer) {\n";
code += " if (_o == null) return;\n"; code += " if (_o == null) return;\n";
code += " serializer.Serialize(writer, _o." + class_member + ");\n"; code += " serializer.Serialize(writer, _o." + class_member + ");\n";
code += " }\n"; code += " }\n";
code += code +=
" public override object ReadJson(Newtonsoft.Json.JsonReader " " public override object ReadJson(Newtonsoft.Json.JsonReader "
@@ -2498,8 +2518,8 @@ class CSharpGenerator : public BaseGenerator {
}; };
} // namespace csharp } // namespace csharp
bool GenerateCSharp(const Parser &parser, const std::string &path, static bool GenerateCSharp(const Parser &parser, const std::string &path,
const std::string &file_name) { const std::string &file_name) {
csharp::CSharpGenerator generator(parser, path, file_name); csharp::CSharpGenerator generator(parser, path, file_name);
return generator.generate(); return generator.generate();
} }
@@ -2514,16 +2534,15 @@ class CSharpCodeGenerator : public CodeGenerator {
return Status::OK; return Status::OK;
} }
Status GenerateCode(const uint8_t *buffer, int64_t length) override { Status GenerateCode(const uint8_t *, int64_t,
(void)buffer; const CodeGenOptions &) override {
(void)length;
return Status::NOT_IMPLEMENTED; return Status::NOT_IMPLEMENTED;
} }
Status GenerateMakeRule(const Parser &parser, const std::string &path, Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename, const std::string &filename,
std::string &output) override { std::string &output) override {
output = CSharpMakeRule(parser, path, filename); output = JavaCSharpMakeRule(false, parser, path, filename);
return Status::OK; return Status::OK;
} }

View File

@@ -90,8 +90,8 @@ class DartGenerator : public BaseGenerator {
template<typename T> template<typename T>
void import_generator(const std::vector<T *> &definitions, void import_generator(const std::vector<T *> &definitions,
const std::string &included, const std::string &included,
std::set<std::string> &imports) { std::set<std::string> &imports) {
for (const auto &item : definitions) { for (const auto &item : definitions) {
if (item->file == included) { if (item->file == included) {
std::string component = namer_.Namespace(*item->defined_namespace); std::string component = namer_.Namespace(*item->defined_namespace);
@@ -760,9 +760,7 @@ class DartGenerator : public BaseGenerator {
std::string getDefaultValue(const Value &value) const { std::string getDefaultValue(const Value &value) const {
if (!value.constant.empty() && value.constant != "0") { if (!value.constant.empty() && value.constant != "0") {
if (IsBool(value.type.base_type)) { if (IsBool(value.type.base_type)) { return "true"; }
return "true";
}
if (IsScalar(value.type.base_type)) { if (IsScalar(value.type.base_type)) {
if (StringIsFlatbufferNan(value.constant)) { if (StringIsFlatbufferNan(value.constant)) {
return "double.nan"; return "double.nan";
@@ -1124,14 +1122,14 @@ class DartGenerator : public BaseGenerator {
}; };
} // namespace dart } // namespace dart
bool GenerateDart(const Parser &parser, const std::string &path, static bool GenerateDart(const Parser &parser, const std::string &path,
const std::string &file_name) { const std::string &file_name) {
dart::DartGenerator generator(parser, path, file_name); dart::DartGenerator generator(parser, path, file_name);
return generator.generate(); return generator.generate();
} }
std::string DartMakeRule(const Parser &parser, const std::string &path, static std::string DartMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name) { const std::string &file_name) {
auto filebase = auto filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(file_name)); flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
dart::DartGenerator generator(parser, path, file_name); dart::DartGenerator generator(parser, path, file_name);
@@ -1154,9 +1152,8 @@ class DartCodeGenerator : public CodeGenerator {
return Status::OK; return Status::OK;
} }
Status GenerateCode(const uint8_t *buffer, int64_t length) override { Status GenerateCode(const uint8_t *, int64_t,
(void)buffer; const CodeGenOptions &) override {
(void)length;
return Status::NOT_IMPLEMENTED; return Status::NOT_IMPLEMENTED;
} }

View File

@@ -28,6 +28,7 @@
#include "flatbuffers/util.h" #include "flatbuffers/util.h"
namespace flatbuffers { namespace flatbuffers {
namespace {
static std::string GenType(const Type &type, bool underlying = false) { static std::string GenType(const Type &type, bool underlying = false) {
switch (type.base_type) { switch (type.base_type) {
@@ -252,8 +253,9 @@ static void GenNameSpace(const Namespace &name_space, std::string *_schema,
} }
// Generate a flatbuffer schema from the Parser's internal representation. // Generate a flatbuffer schema from the Parser's internal representation.
std::string GenerateFBS(const Parser &parser, const std::string &file_name, static std::string GenerateFBS(const Parser &parser,
bool no_log = false) { const std::string &file_name,
bool no_log = false) {
// Proto namespaces may clash with table names, escape the ones that were // Proto namespaces may clash with table names, escape the ones that were
// generated from a table: // generated from a table:
for (auto it = parser.namespaces_.begin(); it != parser.namespaces_.end(); for (auto it = parser.namespaces_.begin(); it != parser.namespaces_.end();
@@ -374,8 +376,8 @@ std::string GenerateFBS(const Parser &parser, const std::string &file_name,
return schema; return schema;
} }
bool GenerateFBS(const Parser &parser, const std::string &path, static bool GenerateFBS(const Parser &parser, const std::string &path,
const std::string &file_name, bool no_log = false) { const std::string &file_name, bool no_log = false) {
const std::string fbs = GenerateFBS(parser, file_name, no_log); const std::string fbs = GenerateFBS(parser, file_name, no_log);
if (fbs.empty()) { return false; } if (fbs.empty()) { return false; }
// TODO: Use LogCompilerWarn // TODO: Use LogCompilerWarn
@@ -387,8 +389,6 @@ bool GenerateFBS(const Parser &parser, const std::string &path,
return SaveFile((path + file_name + ".fbs").c_str(), fbs, false); return SaveFile((path + file_name + ".fbs").c_str(), fbs, false);
} }
namespace {
class FBSCodeGenerator : public CodeGenerator { class FBSCodeGenerator : public CodeGenerator {
public: public:
explicit FBSCodeGenerator(const bool no_log) : no_log_(no_log) {} explicit FBSCodeGenerator(const bool no_log) : no_log_(no_log) {}
@@ -399,11 +399,16 @@ class FBSCodeGenerator : public CodeGenerator {
return Status::OK; return Status::OK;
} }
Status GenerateCodeString(const Parser &parser, const std::string &filename,
std::string &output) override {
output = GenerateFBS(parser, filename, no_log_);
return Status::OK;
}
// Generate code from the provided `buffer` of given `length`. The buffer is a // Generate code from the provided `buffer` of given `length`. The buffer is a
// serialized reflection.fbs. // serialized reflection.fbs.
Status GenerateCode(const uint8_t *buffer, int64_t length) override { Status GenerateCode(const uint8_t *, int64_t,
(void)buffer; const CodeGenOptions &) override {
(void)length;
return Status::NOT_IMPLEMENTED; return Status::NOT_IMPLEMENTED;
} }

View File

@@ -1606,8 +1606,8 @@ class GoGenerator : public BaseGenerator {
}; };
} // namespace go } // namespace go
bool GenerateGo(const Parser &parser, const std::string &path, static bool GenerateGo(const Parser &parser, const std::string &path,
const std::string &file_name) { const std::string &file_name) {
go::GoGenerator generator(parser, path, file_name, parser.opts.go_namespace); go::GoGenerator generator(parser, path, file_name, parser.opts.go_namespace);
return generator.generate(); return generator.generate();
} }
@@ -1622,9 +1622,8 @@ class GoCodeGenerator : public CodeGenerator {
return Status::OK; return Status::OK;
} }
Status GenerateCode(const uint8_t *buffer, int64_t length) override { Status GenerateCode(const uint8_t *, int64_t,
(void)buffer; const CodeGenOptions &) override {
(void)length;
return Status::NOT_IMPLEMENTED; return Status::NOT_IMPLEMENTED;
} }

View File

@@ -69,9 +69,10 @@ static std::set<std::string> JavaKeywords() {
}; };
} }
static const TypedFloatConstantGenerator JavaFloatGen("Double.", "Float.", "NaN", static const TypedFloatConstantGenerator JavaFloatGen("Double.", "Float.",
"POSITIVE_INFINITY", "NaN",
"NEGATIVE_INFINITY"); "POSITIVE_INFINITY",
"NEGATIVE_INFINITY");
static const CommentConfig comment_config = { static const CommentConfig comment_config = {
"/**", "/**",
@@ -79,7 +80,7 @@ static const CommentConfig comment_config = {
" */", " */",
}; };
} // namespace } // namespace
class JavaGenerator : public BaseGenerator { class JavaGenerator : public BaseGenerator {
struct FieldArrayLength { struct FieldArrayLength {
@@ -89,16 +90,15 @@ class JavaGenerator : public BaseGenerator {
public: public:
JavaGenerator(const Parser &parser, const std::string &path, JavaGenerator(const Parser &parser, const std::string &path,
const std::string &file_name, const std::string &file_name, const std::string &package_prefix)
const std::string &package_prefix)
: BaseGenerator(parser, path, file_name, "", ".", "java"), : BaseGenerator(parser, path, file_name, "", ".", "java"),
cur_name_space_(nullptr), cur_name_space_(nullptr),
namer_(WithFlagOptions(JavaDefaultConfig(), parser.opts, path), namer_(WithFlagOptions(JavaDefaultConfig(), parser.opts, path),
JavaKeywords()) { JavaKeywords()) {
if (!package_prefix.empty()) { if (!package_prefix.empty()) {
std::istringstream iss(package_prefix); std::istringstream iss(package_prefix);
std::string component; std::string component;
while(std::getline(iss, component, '.')) { while (std::getline(iss, component, '.')) {
package_prefix_ns_.components.push_back(component); package_prefix_ns_.components.push_back(component);
} }
package_prefix_ = package_prefix_ns_.GetFullyQualifiedName("") + "."; package_prefix_ = package_prefix_ns_.GetFullyQualifiedName("") + ".";
@@ -184,10 +184,8 @@ class JavaGenerator : public BaseGenerator {
code = "// " + std::string(FlatBuffersGeneratedWarning()) + "\n\n"; code = "// " + std::string(FlatBuffersGeneratedWarning()) + "\n\n";
Namespace combined_ns = package_prefix_ns_; Namespace combined_ns = package_prefix_ns_;
std::copy( std::copy(ns.components.begin(), ns.components.end(),
ns.components.begin(), std::back_inserter(combined_ns.components));
ns.components.end(),
std::back_inserter(combined_ns.components));
const std::string namespace_name = FullNamespace(".", combined_ns); const std::string namespace_name = FullNamespace(".", combined_ns);
if (!namespace_name.empty()) { if (!namespace_name.empty()) {
@@ -368,9 +366,9 @@ class JavaGenerator : public BaseGenerator {
FLATBUFFERS_ASSERT(value.type.enum_def); FLATBUFFERS_ASSERT(value.type.enum_def);
auto &enum_def = *value.type.enum_def; auto &enum_def = *value.type.enum_def;
auto enum_val = enum_def.FindByValue(value.constant); auto enum_val = enum_def.FindByValue(value.constant);
return return enum_val
enum_val ? Prefixed(namer_.NamespacedEnumVariant(enum_def, *enum_val)) ? Prefixed(namer_.NamespacedEnumVariant(enum_def, *enum_val))
: value.constant; : value.constant;
} }
std::string GenDefaultValue(const FieldDef &field) const { std::string GenDefaultValue(const FieldDef &field) const {
@@ -703,7 +701,7 @@ class JavaGenerator : public BaseGenerator {
// Force compile time error if not using the same version runtime. // Force compile time error if not using the same version runtime.
code += " public static void ValidateVersion() {"; code += " public static void ValidateVersion() {";
code += " Constants."; code += " Constants.";
code += "FLATBUFFERS_23_5_8(); "; code += "FLATBUFFERS_23_5_26(); ";
code += "}\n"; code += "}\n";
// Generate a special accessor for the table that when used as the root // Generate a special accessor for the table that when used as the root
@@ -1653,9 +1651,9 @@ class JavaGenerator : public BaseGenerator {
break; break;
case BASE_TYPE_UNION: case BASE_TYPE_UNION:
array_type = "int"; array_type = "int";
element_type = element_type = Prefixed(namer_.NamespacedType(
Prefixed(namer_.NamespacedType(*field.value.type.enum_def)) *field.value.type.enum_def)) +
+ "Union"; "Union";
to_array = element_type + ".pack(builder, _o." + to_array = element_type + ".pack(builder, _o." +
namer_.Method("get", property_name) + "()[_j])"; namer_.Method("get", property_name) + "()[_j])";
break; break;
@@ -2007,8 +2005,7 @@ class JavaGenerator : public BaseGenerator {
case BASE_TYPE_UNION: { case BASE_TYPE_UNION: {
if (wrap_in_namespace) { if (wrap_in_namespace) {
type_name = type_name = Prefixed(namer_.NamespacedType(*type.enum_def)) + "Union";
Prefixed(namer_.NamespacedType(*type.enum_def)) + "Union";
} else { } else {
type_name = namer_.Type(*type.enum_def) + "Union"; type_name = namer_.Type(*type.enum_def) + "Union";
} }
@@ -2042,15 +2039,13 @@ class JavaGenerator : public BaseGenerator {
type_name.replace(type_name.length() - type_name_length, type_name.replace(type_name.length() - type_name_length,
type_name_length, new_type_name); type_name_length, new_type_name);
} else if (type.element == BASE_TYPE_UNION) { } else if (type.element == BASE_TYPE_UNION) {
type_name = type_name = Prefixed(namer_.NamespacedType(*type.enum_def)) + "Union";
Prefixed(namer_.NamespacedType(*type.enum_def)) + "Union";
} }
break; break;
} }
case BASE_TYPE_UNION: { case BASE_TYPE_UNION: {
type_name = type_name = Prefixed(namer_.NamespacedType(*type.enum_def)) + "Union";
Prefixed(namer_.NamespacedType(*type.enum_def)) + "Union";
break; break;
} }
default: break; default: break;
@@ -2192,12 +2187,11 @@ class JavaGenerator : public BaseGenerator {
std::string package_prefix_; std::string package_prefix_;
Namespace package_prefix_ns_; Namespace package_prefix_ns_;
}; };
} // namespace java } // namespace java
bool GenerateJava(const Parser &parser, const std::string &path, static bool GenerateJava(const Parser &parser, const std::string &path,
const std::string &file_name) { const std::string &file_name) {
java::JavaGenerator generator(parser, path, file_name, java::JavaGenerator generator(parser, path, file_name,
parser.opts.java_package_prefix); parser.opts.java_package_prefix);
return generator.generate(); return generator.generate();
@@ -2213,16 +2207,15 @@ class JavaCodeGenerator : public CodeGenerator {
return Status::OK; return Status::OK;
} }
Status GenerateCode(const uint8_t *buffer, int64_t length) override { Status GenerateCode(const uint8_t *, int64_t,
(void)buffer; const CodeGenOptions &) override {
(void)length;
return Status::NOT_IMPLEMENTED; return Status::NOT_IMPLEMENTED;
} }
Status GenerateMakeRule(const Parser &parser, const std::string &path, Status GenerateMakeRule(const Parser &parser, const std::string &path,
const std::string &filename, const std::string &filename,
std::string &output) override { std::string &output) override {
output = JavaMakeRule(parser, path, filename); output = JavaCSharpMakeRule(true, parser, path, filename);
return Status::OK; return Status::OK;
} }

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