Squashed 'third_party/flatbuffers/' changes from 338393f85..e5f331db9
e5f331db9 [TS] Add single-file ts codegen & bazel rule for typescript (#7161)
2f84c6038 Apply Namer to Go code gen (#7150)
d64839651 [Lobster] file_identifier support
777e78d8d [Lobster] support unsigned integer reads
4016c549d Apply Namer to Python code gen (#7146)
40827b21b Fix missing 'break' (#7151)
65a10b6e3 Implement a config based name manager and use it in Rust codegen (#7144)
8db2fef3f [TS] Escape keywords in typescript object names (#7137)
9ed132304 Fix 64-bit numeric enum values in typescript (#7135)
1a4c40566 updated npm to 2.0.6
318594e4b prevent name clash (#7133)
3d903302c [Rust] Add length checks to arrays and vectors. (#7130)
c9571d989 Replaced ToDasherCase with ConvertCase (#7131)
3694b830a Use ConvertCase instead of Make{Upper,Lower,Snake} implementations (#7127)
0471fa807 remove stall reference to version
914344ea9 some minor help edits
b40266c56 Use target_compile_features to target C++11 (#7122)
8a9303d46 update proto tests with alaised enum (#7121)
30c4bf47f Trigger fuzzing CI only on relevant changes (#7120)
46ce45601 remove auto generate code from cmakelists (#7119)
433312c55 add the missing checkNullConditionnal code in the "GenObjApi" function when the field is scalar optional (#7114)
9c52ec374 Add deps attribute to flatbuffer_cc_library (#7107)
70e2f49bf fixed string-json -> strict-json typo
5ac0367ed [TS] Fix generation of reserved words in object api (#7106) (#7115)
5d101afb5 Fix minor typo in WhitePaper.md (#7108)
06f4af11b Go optional scalars (#7104)
57e338f81 explicitly use windows-2019 to unblock ci (#7105)
615616cb5 Change Rust generated file defaults (#7101)
3413c3300 Fixed FlexBuffers verifier fuzzer timing out
69f5660a4 Fixed Parser not checking size of union types vector
d5add9fca Fixed FlexBuffers ToString unquoted non-ident keys
15df50eb7 Remove @ExperimentalUnsignedTypes annotation from kotlin code generator. (#7092)
a94132a45 Swift FlatBufferBuilder.sizedByteArray to ByteBuffer.toArray() (#7093)
48befb6be [TS] Refactor away circular ref (#7099)
b30069133 Add reflection support for python (#7026)
faadbc10e Add CreateVector overload to accept array like (#7095)
ed6ae8d32 explicitly defined std::allocator (#7094)
e910bddbc [JS] Add ".js" suffix to all import statements to generate a browser compatible mjs version. (#7086)
c85fb690f Add Parsing Completed function for Rust (#7084)
c1daa6ba0 rust: Bump thiserror version and remove git dependency (#7080)
4c71c7b02 replace framework include of flatbuffers (#7079)
f5664d33f fix go_test implement error (#7012)
39c8a19ce fixed comparator for native_inline (#7076)
826193ff6 skip generating reflection.fbs in generate_scripts (#7077)
fd0d1ed92 update C++ generator to emit scoped enums in vector of unions (#7075)
424988f30 replaced removed xml tag
b2550dbaa removed BSD-3-Clause license and Zlib licenses (#7073)
a2b238960 Fixed default value of bool in struct for Swift (#7072)
619b78437 one last dart omit local (#7070)
68a766154 more omit type annotations for dart local variables (#7069)
7dac9961f omit type annotations for dart local variables (#7067)
c65c389c6 add xmlns to .Net (#7066)
6446dcf3d Updates swift gen licence for grpc code (#7063)
e090d8da1 Fixed long cast to int in flexbufferbuilder.java (#7059)
bc901436d clang format on codebase (#7058)
240be9b5a attempt to remove appveyor (#7056)
bc366a7f9 Provide a short help text and default in error case (#6992)
14b19d446 Use FindPython3 (#7055)
9e6f17b94 remove BIICODE
c3801ad37 Update readme.md
4f3b24db0 Fixes a bug where bools arent being nil when marked optional (#7051)
1d294a31b Implement Serialize on generated rust types (#7022)
dd8fccfb1 Cmake 3.16 de-facto minimum version (#7049)
7089c9ecd Convert flatbuffers_version_string to inline function (#7046)
43203984f [C++] Support C++ object copies and moves (#5988)
5993338ee [ts] Builder incorrectly serializing empty strings (#7047)
19920db39 Include a SizePrefixed..HasIdentifier for c++. (#6871)
dbbaeac85 Use `${PYTHON_EXECUTABLE}` instead of `py` in cmake (#7042)
028f0fde6 'flattest': Add --test_path option (#7041)
87343631b Added support for clang-cl on windows (CMake) (#7038)
1fbfaf5c5 Fix/cmake build grpc (#7028)
4421375bb Add FlatBuffers::FlatBuffers interface, needed for FetchContent_Declare (#7023)
162ad7a37 Fix comment with line orders - Rust should be last. (#7037)
a0a6c3f8c Use actions/checkout@v2, which fixes security vulnerability. (#7036)
a2d38fbb9 Add --warnings-as-errors to flatc compiler. (#7034)
9ef1524d3 Emit include for bfbs-gen-embed (#7031)
0c9de0352 Upgraded GRPC version to 1.42.0 (#7033)
a783bc926 chore: dart 2.0.5 release changes (#6983)
aff818ceb rust: Allow for usage in no_std environment (#6989)
d7b75417f Make flatbuffer builder deterministic (#6993)
a42e89897 Added verifier alignment checking to table fields (#7018)
96cc2f3ee BuildFlatBuffers.cmake: fix arguments not passed properly to flatc (#7013)
3250a1f8d Add initial C# vector of unions support to the documentation. (#6880)
ace4a37f2 [TS/JS] BigInt implementation (#6998)
f28c2b293 Avoid implicit conversion from float to double. (#7003)
96f3cf690 Rearrange #include directives to pass to compilation with a particular DSP toolchain (#7000)
b3edfdbfb Reverting grpc generated file suffix (#6995)
b8aaccee8 Disable parsing of nested_flatbuffers as bytes by default
2dc8ae774 Enable OSS-Fuzz on CI
5b0d49112 Updated FlexBuffers fuzzer
d8b7041d7 Added alignment checking to FlexBuffers verifier
5a0c3366c FlexBuffers verifier additionally checks for nesting
f8148b8da Made FlexBuffers reuse tracker track types
a22b1b626 Prevent shadow with _{{FIELD_NAME}} (#6991)
4264daadd FlexBuffers fuzzer fixes
3cbc120a0 Refractor Flatc Options (#6987)
8dcd2682c [CMake] Add option for disable universal on OSX (#6990)
b78002ff3 Validate C# json/object-api options (#6985)
c555ee8fa Add .NET test to github workflows (#6982)
b92bb0584 [CMake]: Fix version in pkgconfig file (#6986)
956d11569 re-enabled FlexBuffer JSON in fuzzer
e367ca32a Verifier for FlexBuffers (#6977)
705f27f6e [CMake]: Fix python command for mingw environment (#6984)
5fc87f4c4 Enable --gen-onefile in Python (#6953)
11749095a Make idl_parser deterministic (#6976)
d0cede9c9 Bumping to Version 2.0.5 (#6967)
fcc2bee0b Fix typo in variable name (#6973)
e08da4dea remove Appveyor's Vs2010 and 13 builds (#6969)
18538c401 [TS] Fix reserved words as arguments (#6955) (#6956)
e57f4ab2d Update stale bot version and provide away to exempt issues with the not-stale label (#6968)
deed68db5 missing generated files (#6966)
061d61f3f Lua Generator using IR. (#6940)
cffe0c454 FixedTypedVector: add const to ElementType() and size() (#6965)
fadd40e40 Have grpc include file with correct filename-suffix given to flatc (#6954)
e47dc0e46 Removed test/generate_code.{sh|bat} (#6873)
5c5475479 switched to windows-lastest, removed deadcode (#6948)
4f7f6dc30 Restore FlatBufferBuilder::kFileIdentifierLength. (#6960)
0fadaf391 Enable verifier on nested_flatbuffers
4d0e9a870 Turn off nested FlatBuffers/FlexBuffers for the fuzzer
c05f6783a invalid conditional running genrate_code.py (#6952)
a14f4052c rust: remove needless borrow (#6922)
9e4ca857b Vector Downward GetSize optimization (#6925)
a2b99084b Fix flexbuffers clang-analyzer warning (#6947)
85b4effac test: fix undefined order of functio parameters. (#6946)
790f41154 [cmake] Fix getting version info from tags during the build (#6936)
e89de4411 clang-all (#6941)
256ab3798 WIP: Dart release 2.0 (#6927)
a59288a01 Add benchmarks to Linux CI (#6928)
587bbd49a [C++] Fix compile failure on Object API union construction for struct member (#6923)
a9c341545 Fix integer overflow warnings
8aa18b629 fixed cmp0048 error (#6932)
d727579b6 fuzzers: fix typo in file path (#6931)
97a30171c Added Raw C++ benchmarks (#6924)
0989fc5e5 Added Google benchmarks (and gtests) (#6920)
927175ea2 [Java] lookup by byteArray is giving back wrong entry (#6915)
6748c373b Removal of support for FLATBUFFERS_CPP98_STL (#6918)
3fab0c6ee move [[ ]] to calling sites (#6914)
6c8c29155 [C++] Split flatbuffers.h into separate files (#6868)
fd4ff23da Keep methods with struct name and switch them to default (#6879)
f8b69e330 [Python] Verify EnumDef is not generated in GenUnionCreator (#6903)
c0394bb09 Support `--conform` for vector of unions (#6883)
8433eb108 Typo fixes in comments of flatbuffers.h and flexbuffers.h (#6901)
f2f9380c8 [Java] Prevent generation of enum names when underlying type is long (#6781) (#6895)
e672dabfe [C++] Fix memory leak when using grpc (#6896) (#6897)
9a4ca2764 Output errors / warnings on stderr instead of stdout (#6881)
4c7a9c10d Adds JSON encoding to swift (#6874)
38295a187 [Kotlin] Fix missing escape for struct construction statements (#6877)
31bb0b972 add working directory (#6878)
45e5642e9 Default Arguments for Mutators C++ [Updated] (#6872)
a592f4c89 [Cmake] Add a post build command after flatc to run the new generate_code.py script. (#6866)
b9d43a557 dart - add Packable interface (#6846)
2ece9e25b Bumped package.json to 2.0.4
2dd212637 Fix linker errors on (Free|Open)BSD. (#6860)
f63c130c2 Improves documentation, and adding DocC (#6784)
e2b26ee19 Make and generate_code.sh generate same outputs (#6855)
9d686bf43 Include subdirectories in published npm package (#6850)
1d26daff3 Use ArrayBuffer type for JS flexbuffer's toObject (#6851)
e72e18d9f feat(build): compile "universal" libraries and executables for Mac (#6852)
354d97f6d fixed errant itemgroup element in C# test project (#6854)
6f7a57eaa [C#] Using 'global::' as qualifying_start_ within BaseGenerator (#6767)
90baa1444 Dart: binary lists (typed_data) (#6839)
0a3b017f0 Delete IDLOptions::lang (#6841)
47d35f105 BugFix: Optional enum when it is null (#6835)
8fb8c2ce1 [C#] Use @ for keyword escaping (#6834)
1d063d87c [C++] Let builder accept custom-alloc std::vector (#6814)
338331b55 Changes to support binary schema file loading and parsing (flatc) (#6823)
156a30c75 Move Apple-specific build flags to Clang section (#6802)
550d2f904 Issue error if jsonschema has no root type defined #6821 (#6831)
c3a38242e Fix typos in docs (#6829)
74c3d7eba [C++] Add mutable version of LookupByKey and test (#6826)
db6eae5c4 Add html and latex to gitignore (#6819)
0e9d79c35 [Java] Avoid casting ByteBuffer to Buffer (#6785)
b20c4d3aa [C++] Add GetMutableSizePrefixedRoot and generate GetMutableSizePrefixedXxx functions (#6815)
ae145293c flattests_cpp17 doesn't compile with Visual Studio 2017: warning C4100: 'indent': unreferenced formal parameter (#6811)
e3c76a5cd Dart lints (#6808)
4b9123baf fix parser string=null (#6810)
f89e0b1a6 Refactor idl_gen_rust and Rust generated code to use consistent whitespace (#6809)
273f6084e Fix Rust keyword inconsistency (#6794)
4a0879458 [C#] Remove superfluous semicolon in C# structs (#6791)
d6f51ea16 fix ptr in flatbuffers cpp tutorial (#6787)
067dce6e7 [C#] Handle keywords (#6775)
2ca5f0e72 [C#] Respect command line parameter for file name extension and suffix (#6779)
f20d2253a update Java version to 2.0.3
390d438e2 [Kotlin] Fix CI by changing compiler to Java 11 (#6783)
6fb2c90d9 avoiding even more NoSuchMethod exceptions (#6729)
a7b527d94 java: Use maven profile to target Java 8 bytecode (#6764)
5d77820b3 [C++] Using calculated fields_number for field_names size (#6769)
909ce970a [C++] Use UnPackTo instead of UnPack if pointer exists (#6725)
35e2cac6e Store vtables sorted in Rust builder (#6765)
c39fc9dd9 [C++] Use nullptr instead of 0 in generated headers (#6762)
775c6567d [C++] Fix compiler warning -Wredundant-parens in clang (#6761)
97d9527f6 Dart 2.0 release prep (#6759)
e01205466 [C++] Use proper gRPC C++ API when using MemoryBuffer Slice (#6756)
5235133f3 Dart - make ascii optimization optional in StringReader, same as in writeString() (#6758)
c871df770 Dart - change table building to assert() instead of exceptions (#6754)
a6eeeb3b9 Dart - inline small functions to increase performance (#6755)
3dd02144d [C#] Fix field name struct name collision (#6744) (#6757)
e77926f0e [C#] Add Union Constructor Utility for ObjectAPI. (#6105)
ac2348202 Dart - fixup writeString() return type after previous merges (#6753)
8be8a0a71 [C++] Fix union type handling on object api in C++17 (#6745)
12e341e4f Rework how Rust generated files are laid out (#6731)
c36672d80 Dart - optimize writeString for ASCII (#6736)
2bfc8e9f0 Dart - make writeString() argument non-nullable (#6737)
674a9f2aa fix lints in rust tests (#6743)
016e6aa13 Add a split on ':' to build_defs.bzl (#6742)
65700441d Dart - make vTable fixed size (expect the number of fields when creating) (#6735)
dd5bb55ca Dart - make vTable deduplication optional (#6734)
e8423da1b Dart - regenerate example after recent flatc changes (#6733)
0980e39c9 flexbuffers: Add variant of Blob() that takes a key (#6730)
e73fab27d Dart - store empty vectors instead of NULL (#6728)
92ae532e4 Dart - finish/lowFinish/buffer changes (#6712)
7482b25f8 Remove ubuntu1604 from presubmit.yml (#6715)
3f77dc9a0 Dart - unpack() must use eager list reader (#6723)
838c93b84 Dart - fix flex-builder compilation error (#6722)
089f48a4a Dart - make sure added padding is zeroed, same as in C++ (#6716)
bf3470c16 Fix UB in CreateVectorOfStructs in case of an empty vector: avoid calling memcpy in this case (#6726)
8f8196e13 Fix 6348 (#6717)
8ab35b2a5 Dart - add custom allocator support (#6711)
c0ba2870c Fix typo in docu (#6714)
22498cf3a [C++] add make_span for Array<T,N> (#6663)
bd37e67ac [C++] Fix a -Wdeprecated-copy warning. (#6708)
a6ee33557 Dart null safety (#6696)
71d43f3be Make --bfbs-filenames default to location of first schema file. (#6705)
c8db1ca5d Jsonschema add prop comments (#6617)
962751a6e Improve generated comparisons for tables (#6486)
06fd6d640 Replace filenames in reflection with filenames+includes. (#6703)
acce4ac3f Fix incorrect assertion usage. (#6702)
8fd7861b7 Fix warning about deprecated module: imp (#6362)
c58ae9422 Add the file a symbol is declared in to Reflection (#6613)
2cf7bb796 Intermediate Representation docs (#6685)
4e3a66c14 Dart object API (#6682)
d959e2320 dart - change Builder.reset() to reuse an existing buffer (#6661)
a9fb54088 use improved versioning (#6691)
337eb8b8f update docs - structs can't be roots (#6690)
6415ef05d [Python] [Codegen] Fixes nested structs with underscore names (#6686)
f069396d1 [C++] flatc --cpp-field-case-style option to permit camel-case field names in C++ (#6669)
021177af0 Fix snap version formatting (#6683)
e1e9f9373 [C++/grpc] added hiding of unused variables in the generated code (#6677)
15110094e Fix GitHub Actions CI gcc/clang versions
093badb0a Use unoptimized path for ReadUInt64 for win32 build as the optimized path crashes. (#6681)
752c7b576 avoiding more NoSuchMethod exceptions (#6671)
7c3e267e1 [Java] ObjectAPI implementation (#6521) (#6582)
baaffbaed npm update to 2.0.3 and script fix
4cb3f222b [TS] Fix module reference in package.json (#6676)
eabdbda75 [TS] Generate entry point module (#6674)
bec23700f Prepare for Java 2.0.1 release
12f2eedad Update CI to GCC/Clang 11
221eeb231 Fix typo in C++ doc (#6664)
813d3632e avoiding NoSuchMethod exception (#6658)
d84bccb0c Removed most heap allocations in builder (#6662)
b4e67f9bf Dart test fix (#6660)
54c11932f [Java] Flexbuffers - Negative signed object length (#6651)
fbcb3c423 [TS/JS] Updates the grpc (#6654)
8937dcfd7 Updates go lang support to allow other languages to communicate with it (#6653)
512d5a689 Update readme.md to point to security policy
a92cb5dd7 Create Security.md
d151dcbb9 Revert "[C++] Removed most heap allocations in builder (#6620)" (#6659)
f1884c66f Fix gRPC test to use EndVector without specifying the length. (#6646)
72730ecd8 [C++] Removed most heap allocations in builder (#6620)
fe2bc2b0a Added README for Rust Flatbuffers (before publishing v=2.0) (#6652)
4867c9456 Fixed generation of c++ code with flags (#6637)
ef0eb3701 Ran clang-format-all.sh. Removed default --style=file parameter (#6639)
f83ee1af5 [idl_parser] Check structs and enums do not clash in a namespace (#6562)
a5175c513 Implements verifier and code gen for swift (#6373)
04b10f5a3 Deprecate EnumVal.object (#6612)
c121c0345 Fixed Java gRPC version number dependency
8fd10606c Implement Serialize for flexbuffer::Reader (#6635)
a1730fcea [Swift] Updated cocoapods to 2.0.0 (#6634)
a9a295fec More missing version changes
5c01ad387 Dart generated code update
42ca1b914 Swift/Kotlin generated code version updates
6ed780dbd C++/Rust version changes
3412fab8e C#/Java generated code version updates
8a7d013f8 Updated main version numbers to 2.0
170af5978 [Go] Add missing namespace when using Object API (#6633)
c8c16de16 Fix reverse iterators for Vector and Array (#6626)
4525cd9c5 [Lua] manipulate byte array as string (#6624)
47361baf6 [C++] Fix union copy constructor to work with nested structs (#6552) (#6607)
8a582883a Updates swift generated monster sample file (#6616)
a4bb8f0c2 [Lua] Avoid infinite loop when creating empty string (#6614)
82aed82b8 Added support for Lua 5.1, 5.2 and 5.4 (#6606)
60ff76630 [TS] Remove wrong and obsolete NS prefix use (#6604)
a27c7d809 Fixed LuaJIT when not compiled with COMPAT mode (#6605)
363220823 removed unneeded type prefixing (#6601)
6b44c605b Bump Rust to 0.9.0 (#6610)
d3cd78a87 [Lua] Add LuaJIT support (#6584)
8fa3dfdb5 Introduce new_from_vec in Rust (also fix formatting) (#6599)
29379e8e4 fix typo in CppUsage.md (#6595)
14725d6c3 [Lua] GetRootAs can accept strings. Made Luatest Benchmarks optional (#6593)
16836ff95 Add advance feature indicators to reflection (#6546)
c87179e73 Rust Remove SafeSliceAccess for Arrays, and fix miri. (#6592)
c24031c36 Mark endian_scalar as unsafe. (#6588)
4ccc52c7a [swift] Implements union strings (#6589)
b82fe0738 [Rust] Fix small mistyping (#6585)
1e7f6c8c7 [TS] Commit the generated tests code (#6579)
84714b109 chore: ensure bash is used to generate code (#6577)
1045d7dd4 [Lua] Fix EnforceNumberAndPack for bool type (#6576)
0c7777596 [TS] Remove duplicated build-ts ci (#6575)
c43ba1752 [Rust] Specify Minimum Supported Rust Version (#6573)
da3bb64ef [Rust] Add support for fixed size arrays (#6548)
151900ba9 [Kotlin][FlexBuffers] Add support for Kotlin-iOS (#6564)
c012f29f9 silenced clippy warning (#6565)
df2df21ec [Kotlin] Bump kotlinx.benchmark dependency to 0.3.0 (#6560)
408e4db4a [TS] Add Build TS to CI jobs (#6524)
4d2364f34 [Kotlin][FlexBuffers] Add support for Kotlin-JS (#6554)
261cf3b20 Default-empty vectors of enums (#6505)
cd67261bb [CI] fixes buildkite (#6544)
1aa0c2f6a Limit formatter to pull requests only (#6540)
4133a39df Rust structz (#6539)
1c26d2a1a [Kotlin][FlexBuffers] JSON support for Flexbuffers (#6417)
276b1bc34 [grpc] Support latest version of grpc PoC (#6338)
124654ffc fixed packing structs (#6530)
3b7d1e86b [GO] Tries to add go format to the CI (#6518)
78f0c0d1d [C++] #6501 - Problem when mapping a native type multiple times (#6514)
c992eafb5 [fuzzer] Add `monster_debug` target (#6513)
ef8dd7792 [Swift] Removes allman rule (#6519)
69b329fc8 [flexbuffers, json] Parse `nan` and `inf` (#6512)
6543ba529 fixed packing structs in nested buffers (#6509)
0e453ac35 [idl_parser] Add kTokenNumericConstant token (#6432)
e9b4ae69d Remove `flatbuffers.pc` from the repository (#6508)
fc4fffea4 Bump grpc to 1.0.0 (#6507)
b240ab704 Move Traits struct and Create method out of --cpp-static-reflection. (#6503)
9a4f1f434 Disable x64-specific optimizations for ARM64EC ReadInt64 (#6506)
fac64918d Add --cpp-static-reflection to generate_code.bat. (#6502)
a69815f72 [C++17] Add compile-time reflection for fields. (#6324)
4033ff589 fixed invalid TS call and added test files (#6495)
a08357251 disable clippy (#6494)
5319dedb1 [idl_parser, JSON] Disable parsing of JSON for incomplete schemes (#6493)
bd4e0b30a [idl_parser] Track included files by hash (#6434)
bf9061200 fix for noUncheckedIndexedAccess in ts (#6474)
8142fedd1 Working on a python example plus fixing python grpc code (#6456)
c0be1cb7a [rust] Remove debug code (#6475)
8cccdfba5 Revert "[C#] Fix truncated ArraySegment<byte> if elementSize != 1 (#6462)" (#6488)
cbbbaa61b [C#] Fix truncated ArraySegment<byte> if elementSize != 1 (#6462)
ffc2ef77c [CI] Adds Code Generation tests on Github Actions (#6482)
1da6f4f18 [CMake] generate pkg-config flatbuffers.pc file (#6455)
b5da526e6 [Swift] Moves grpc example to grpc/examples (#6479)
3b5365762 [TS] Moves grpc code to examples folder (#6476)
e2f5438ac Fixes grammer (#6477)
5e3613f73 Fix sample_binary.py to use latest EndVector without a size. (#6478)
e6b911d40 updated JS docs to reflect current status (#6436)
0c7ae5816 [Go] Working on a go example plus fixing go grpc code (#6448)
ae603b977 [Swift] adds support for default vectors and strings (#6461)
7f47718b6 Update Building.md (#6473)
54dc09e8a GetUOffsetT must get value by GetUint32 not GetInt32 (#6072)
334c6be49 Fix a typo in Swift codegen (#6470)
4174c10e7 [rust] Genericize flexbuffer reader (#6450)
a20f606c2 [Swift] Renaming protocols (#6469)
a72a20827 Update swift docs (#6460)
86401e078 Default strings and vectors: Parser + Rust support (#6421)
6af37e672 [CMake] Renames BUILD files (#6457)
1b88655b0 [Build, cmake] Add -Werror override option (#6429)
0b15916e5 [C++]Fix extra char generation for byte type during json schema generation (#6276)
60eed0ca6 Updating working code (#6441)
0f83367f5 JSON schema - tailing double quotes for maximum (#6452)
fee095410 [idl_parser] Validate `force_align` on all possible paths (#6430)
6f3e45eca Implement Rust object API defaults (#6444)
815d3e820 Upgrade swift grpc to alpha 24 (#6439)
76e7a0ff5 [fuzzer] Limit parser_fuzzer execution time (#6431)
6d91096a2 This commit contains the initial implementation of Flexbuffers in Kotlin. The code was ported based (#6387)
13d9e3585 Better python generated code naming (#6336)
6effe431b Rust: remove inner attributes (#6410)
efcbdc769 [Rust] Ensure unions are referenced with the correct path (#6422)
e581013e3 Refactor FieldDef to model presense as an enum rather than 2 bools. (#6420)
0984d4328 [c++] Apply NativeName before WrapInNameSpace in idl_gen_cpp.cpp (#6419)
786f69b24 Formats cpp code (#6349)
1da0a2dfa Rust Object API (#6070)
796ed68fa Clarify that (Flat|Flex)Buffers do not deduplicate vector elements (#6415)
7b1ee31d8 Clarify that FlatBuffers unions do not support scalars (#6416)
4aff1198d Explain how FlatBuffers encodes unions (#6414)
ad3a729f9 dart Builder - expose finished buffer size (#6403)
52e217706 Remove invalid claim that Protocol Buffers does not support unions (#6413)
760c65755 [TS/JS] New gen TS code gen (#6302)
75c859e98 [idl_parser] Improve symbols lookup thru parent namespaces (#6407)
91b0958c4 Search for includes in the directory containg the current file (#6371)
8008dde11 Upgrade Rust dependencies (#6406)
c81cf8249 [TS/JS] New gen TS code gen prequel to preserve history (#6404)
8573108bb Unset FieldDef.optional if its key (#6402)
7abe612b5 [fuzzer] Fix the binary schema loading in the monster_fuzzer (#6396)
408cf5802 Fix Rust UB problems (#6393)
39e115fdb Define Vector::value_type for STL compatibility (#6394)
85719669c [fuzzer] Debug the monster_tets.bfbs on clusterfuzz server (#6392)
809fe49c7 Fix up scripts, fix generated enum value for strong mode, regenerate files (#6389)
41253e574 [go] tests/GoTest.sh: Fix flags.Parse location to work on new go SDKs. (#6388)
08d2ce844 fix Dart Builder._writeString() - always write trailing zero byte (#6390)
a15a8d930 fix Dart Builder.reset() - clear vTables (#6386)
83ce29cc2 [C++, JSON] Fix nullptr access when reading a key with a default value. (#6375)
4363c1d2c Fix generated EndVector. (#6385)
1bf1ec027 Implements type promotion for Java enum (#6382)
080097653 Delete label_notify.yml
795408115 Disabled PHP CI (#6381)
46545e627 fixed warnings (#6355)
0168178a1 Fix multiple fbs code generation failure (#6365)
82836a62b [idl_parser] Improve stack overflow protection (#6364)
e7430bbeb [idl_parser] Check the range of explicitly set field's id value (#6363)
24dd85fd2 Generate code to encode and decode nested flatbuffers in Python. (#6354)
57f68e289 [Rust] Shared String (#6367)
44cf2bde1 Updates license date to 2021 (#6378)
be37d4da1 include_prefix support for rust (#6330)
4e79d129c [Swift] Rebuild the way swift handles structs from scratch (#6326)
05192553f Fix typos in usage/comments; Make rust generator respect to --filenam… (#6342)
f2511d7d4 Renaming infinity variables in test.cpp (#6340)
f8b203c9c Add vectorNumElements attribute to Builder for simpler vector creation. (#6328)
8ab7c7e2c [CI] Adds formatter to CI (#6272)
7e0039028 Fix Max CI build path (#6333)
65c415911 Generate nullable properties in C# object-based API for optional scalars. (without -gen-mutable) (#6273)
a9e91116d [Python] Commit some orphan python genfile diffs. (#6325)
80a745d9b Fixed missing ending quotes in labeller (#6327)
9fca5e4f4 Add flatc option to inhibit all warnings #6005 (#6301)
92a806b4e [fuzzer] Rename fuzzing dictionaries for `oss-fuzz` (#6318)
9c9baf6d5 bumprust (#6322)
aafc5dc95 Set default initialSize for Builder to 0 (#6310)
442949bc1 Rust Flatbuffers Verifier (#6269)
9064072e8 Version message should be a "STATUS" to avoid going to stderr. (#6316)
fd4c1b5ff Replace std::string and const char* CreateSharedString with string_view (#6315)
bc7eb8ade [fuzzer] Fix mistakes in the `parser` and `scalar` fuzzers. (#6314)
fc960f367 Add default to offset param of Python generated GetRootAs (#6312)
f437f0f7e [fuzzer] Fix loading of schema in monster_fuzzer (#6308)
7f33cf682 [C++] Switch `flatc` to `--cpp-std c++11` C++ code generator (#6306)
8d9eae9ac [idl_parser] Unify parsing of NaN values read from .fbs and .json files (#6296)
2046bffa4 Moved various language tests from AppVeyor to GitHub Actions (#6300)
git-subtree-dir: third_party/flatbuffers
git-subtree-split: e5f331db998a808f78cf5a4880e6f5d0a321c4d0
Signed-off-by: James Kuszmaul <jabukuszmaul+collab@gmail.com>
Change-Id: I37f8aaf007fc86226cfa250169a87807afa64a78
diff --git a/include/flatbuffers/flatbuffers.h b/include/flatbuffers/flatbuffers.h
index 1f25d4e..6421788 100644
--- a/include/flatbuffers/flatbuffers.h
+++ b/include/flatbuffers/flatbuffers.h
@@ -17,2628 +17,23 @@
#ifndef FLATBUFFERS_H_
#define FLATBUFFERS_H_
+// TODO: These includes are for mitigating the pains of users editing their
+// source because they relied on flatbuffers.h to include everything for them.
+#include "flatbuffers/array.h"
#include "flatbuffers/base.h"
+#include "flatbuffers/buffer.h"
+#include "flatbuffers/buffer_ref.h"
+#include "flatbuffers/detached_buffer.h"
+#include "flatbuffers/flatbuffer_builder.h"
#include "flatbuffers/stl_emulation.h"
-
-#ifndef FLATBUFFERS_CPP98_STL
- #include <functional>
-#endif
-
-#if defined(FLATBUFFERS_NAN_DEFAULTS)
-# include <cmath>
-#endif
+#include "flatbuffers/string.h"
+#include "flatbuffers/struct.h"
+#include "flatbuffers/table.h"
+#include "flatbuffers/vector.h"
+#include "flatbuffers/vector_downward.h"
+#include "flatbuffers/verifier.h"
namespace flatbuffers {
-// Generic 'operator==' with conditional specialisations.
-// T e - new value of a scalar field.
-// T def - default of scalar (is known at compile-time).
-template<typename T> inline bool IsTheSameAs(T e, T def) { return e == def; }
-
-#if defined(FLATBUFFERS_NAN_DEFAULTS) && \
- defined(FLATBUFFERS_HAS_NEW_STRTOD) && (FLATBUFFERS_HAS_NEW_STRTOD > 0)
-// Like `operator==(e, def)` with weak NaN if T=(float|double).
-template<typename T> inline bool IsFloatTheSameAs(T e, T def) {
- return (e == def) || ((def != def) && (e != e));
-}
-template<> inline bool IsTheSameAs<float>(float e, float def) {
- return IsFloatTheSameAs(e, def);
-}
-template<> inline bool IsTheSameAs<double>(double e, double def) {
- return IsFloatTheSameAs(e, def);
-}
-#endif
-
-// Check 'v' is out of closed range [low; high].
-// Workaround for GCC warning [-Werror=type-limits]:
-// comparison is always true due to limited range of data type.
-template<typename T>
-inline bool IsOutRange(const T &v, const T &low, const T &high) {
- return (v < low) || (high < v);
-}
-
-// Check 'v' is in closed range [low; high].
-template<typename T>
-inline bool IsInRange(const T &v, const T &low, const T &high) {
- return !IsOutRange(v, low, high);
-}
-
-// Wrapper for uoffset_t to allow safe template specialization.
-// Value is allowed to be 0 to indicate a null object (see e.g. AddOffset).
-template<typename T> struct Offset {
- uoffset_t o;
- Offset() : o(0) {}
- Offset(uoffset_t _o) : o(_o) {}
- Offset<void> Union() const { return Offset<void>(o); }
- bool IsNull() const { return !o; }
-};
-
-inline void EndianCheck() {
- int endiantest = 1;
- // If this fails, see FLATBUFFERS_LITTLEENDIAN above.
- FLATBUFFERS_ASSERT(*reinterpret_cast<char *>(&endiantest) ==
- FLATBUFFERS_LITTLEENDIAN);
- (void)endiantest;
-}
-
-template<typename T> FLATBUFFERS_CONSTEXPR size_t AlignOf() {
- // clang-format off
- #ifdef _MSC_VER
- return __alignof(T);
- #else
- #ifndef alignof
- return __alignof__(T);
- #else
- return alignof(T);
- #endif
- #endif
- // clang-format on
-}
-
-// When we read serialized data from memory, in the case of most scalars,
-// we want to just read T, but in the case of Offset, we want to actually
-// perform the indirection and return a pointer.
-// The template specialization below does just that.
-// It is wrapped in a struct since function templates can't overload on the
-// return type like this.
-// The typedef is for the convenience of callers of this function
-// (avoiding the need for a trailing return decltype)
-template<typename T> struct IndirectHelper {
- typedef T return_type;
- typedef T mutable_return_type;
- static const size_t element_stride = sizeof(T);
- static return_type Read(const uint8_t *p, uoffset_t i) {
- return EndianScalar((reinterpret_cast<const T *>(p))[i]);
- }
-};
-template<typename T> struct IndirectHelper<Offset<T>> {
- typedef const T *return_type;
- typedef T *mutable_return_type;
- static const size_t element_stride = sizeof(uoffset_t);
- static return_type Read(const uint8_t *p, uoffset_t i) {
- p += i * sizeof(uoffset_t);
- return reinterpret_cast<return_type>(p + ReadScalar<uoffset_t>(p));
- }
-};
-template<typename T> struct IndirectHelper<const T *> {
- typedef const T *return_type;
- typedef T *mutable_return_type;
- static const size_t element_stride = sizeof(T);
- static return_type Read(const uint8_t *p, uoffset_t i) {
- return reinterpret_cast<const T *>(p + i * sizeof(T));
- }
-};
-
-// An STL compatible iterator implementation for Vector below, effectively
-// calling Get() for every element.
-template<typename T, typename IT> struct VectorIterator {
- typedef std::random_access_iterator_tag iterator_category;
- typedef IT value_type;
- typedef ptrdiff_t difference_type;
- typedef IT *pointer;
- typedef IT &reference;
-
- VectorIterator(const uint8_t *data, uoffset_t i)
- : data_(data + IndirectHelper<T>::element_stride * i) {}
- VectorIterator(const VectorIterator &other) : data_(other.data_) {}
- VectorIterator() : data_(nullptr) {}
-
- VectorIterator &operator=(const VectorIterator &other) {
- data_ = other.data_;
- return *this;
- }
-
- // clang-format off
- #if !defined(FLATBUFFERS_CPP98_STL)
- VectorIterator &operator=(VectorIterator &&other) {
- data_ = other.data_;
- return *this;
- }
- #endif // !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
-
- bool operator==(const VectorIterator &other) const {
- return data_ == other.data_;
- }
-
- bool operator<(const VectorIterator &other) const {
- return data_ < other.data_;
- }
-
- bool operator!=(const VectorIterator &other) const {
- return data_ != other.data_;
- }
-
- difference_type operator-(const VectorIterator &other) const {
- return (data_ - other.data_) / IndirectHelper<T>::element_stride;
- }
-
- IT operator*() const { return IndirectHelper<T>::Read(data_, 0); }
-
- IT operator->() const { return IndirectHelper<T>::Read(data_, 0); }
-
- VectorIterator &operator++() {
- data_ += IndirectHelper<T>::element_stride;
- return *this;
- }
-
- VectorIterator operator++(int) {
- VectorIterator temp(data_, 0);
- data_ += IndirectHelper<T>::element_stride;
- return temp;
- }
-
- VectorIterator operator+(const uoffset_t &offset) const {
- return VectorIterator(data_ + offset * IndirectHelper<T>::element_stride,
- 0);
- }
-
- VectorIterator &operator+=(const uoffset_t &offset) {
- data_ += offset * IndirectHelper<T>::element_stride;
- return *this;
- }
-
- VectorIterator &operator--() {
- data_ -= IndirectHelper<T>::element_stride;
- return *this;
- }
-
- VectorIterator operator--(int) {
- VectorIterator temp(data_, 0);
- data_ -= IndirectHelper<T>::element_stride;
- return temp;
- }
-
- VectorIterator operator-(const uoffset_t &offset) const {
- return VectorIterator(data_ - offset * IndirectHelper<T>::element_stride,
- 0);
- }
-
- VectorIterator &operator-=(const uoffset_t &offset) {
- data_ -= offset * IndirectHelper<T>::element_stride;
- return *this;
- }
-
- private:
- const uint8_t *data_;
-};
-
-template<typename Iterator>
-struct VectorReverseIterator : public std::reverse_iterator<Iterator> {
- explicit VectorReverseIterator(Iterator iter)
- : std::reverse_iterator<Iterator>(iter) {}
-
- typename Iterator::value_type operator*() const {
- return *(std::reverse_iterator<Iterator>::current);
- }
-
- typename Iterator::value_type operator->() const {
- return *(std::reverse_iterator<Iterator>::current);
- }
-};
-
-struct String;
-
-// This is used as a helper type for accessing vectors.
-// Vector::data() assumes the vector elements start after the length field.
-template<typename T> class Vector {
- public:
- typedef VectorIterator<T, typename IndirectHelper<T>::mutable_return_type>
- iterator;
- typedef VectorIterator<T, typename IndirectHelper<T>::return_type>
- const_iterator;
- typedef VectorReverseIterator<iterator> reverse_iterator;
- typedef VectorReverseIterator<const_iterator> const_reverse_iterator;
-
- uoffset_t size() const { return EndianScalar(length_); }
-
- // Deprecated: use size(). Here for backwards compatibility.
- FLATBUFFERS_ATTRIBUTE(deprecated("use size() instead"))
- uoffset_t Length() const { return size(); }
-
- typedef typename IndirectHelper<T>::return_type return_type;
- typedef typename IndirectHelper<T>::mutable_return_type mutable_return_type;
-
- return_type Get(uoffset_t i) const {
- FLATBUFFERS_ASSERT(i < size());
- return IndirectHelper<T>::Read(Data(), i);
- }
-
- return_type operator[](uoffset_t i) const { return Get(i); }
-
- // 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 E.
- template<typename E> E GetEnum(uoffset_t i) const {
- return static_cast<E>(Get(i));
- }
-
- // If this a vector of unions, this does the cast for you. There's no check
- // to make sure this is the right type!
- template<typename U> const U *GetAs(uoffset_t i) const {
- return reinterpret_cast<const U *>(Get(i));
- }
-
- // If this a vector of unions, this does the cast for you. There's no check
- // to make sure this is actually a string!
- const String *GetAsString(uoffset_t i) const {
- return reinterpret_cast<const String *>(Get(i));
- }
-
- const void *GetStructFromOffset(size_t o) const {
- return reinterpret_cast<const void *>(Data() + o);
- }
-
- iterator begin() { return iterator(Data(), 0); }
- const_iterator begin() const { return const_iterator(Data(), 0); }
-
- iterator end() { return iterator(Data(), size()); }
- const_iterator end() const { return const_iterator(Data(), size()); }
-
- reverse_iterator rbegin() { return reverse_iterator(end() - 1); }
- const_reverse_iterator rbegin() const {
- return const_reverse_iterator(end() - 1);
- }
-
- reverse_iterator rend() { return reverse_iterator(begin() - 1); }
- const_reverse_iterator rend() const {
- return const_reverse_iterator(begin() - 1);
- }
-
- const_iterator cbegin() const { return begin(); }
-
- const_iterator cend() const { return end(); }
-
- const_reverse_iterator crbegin() const { return rbegin(); }
-
- const_reverse_iterator crend() const { return rend(); }
-
- // Change elements if you have a non-const pointer to this object.
- // Scalars only. See reflection.h, and the documentation.
- void Mutate(uoffset_t i, const T &val) {
- FLATBUFFERS_ASSERT(i < size());
- WriteScalar(data() + i, val);
- }
-
- // Change an element of a vector of tables (or strings).
- // "val" points to the new table/string, as you can obtain from
- // e.g. reflection::AddFlatBuffer().
- void MutateOffset(uoffset_t i, const uint8_t *val) {
- FLATBUFFERS_ASSERT(i < size());
- static_assert(sizeof(T) == sizeof(uoffset_t), "Unrelated types");
- WriteScalar(data() + i,
- static_cast<uoffset_t>(val - (Data() + i * sizeof(uoffset_t))));
- }
-
- // Get a mutable pointer to tables/strings inside this vector.
- mutable_return_type GetMutableObject(uoffset_t i) const {
- FLATBUFFERS_ASSERT(i < size());
- return const_cast<mutable_return_type>(IndirectHelper<T>::Read(Data(), i));
- }
-
- // The raw data in little endian format. Use with care.
- const uint8_t *Data() const {
- return reinterpret_cast<const uint8_t *>(&length_ + 1);
- }
-
- uint8_t *Data() { return reinterpret_cast<uint8_t *>(&length_ + 1); }
-
- // Similarly, but typed, much like std::vector::data
- const T *data() const { return reinterpret_cast<const T *>(Data()); }
- T *data() { return reinterpret_cast<T *>(Data()); }
-
- template<typename K> return_type LookupByKey(K key) const {
- void *search_result = std::bsearch(
- &key, Data(), size(), IndirectHelper<T>::element_stride, KeyCompare<K>);
-
- if (!search_result) {
- return nullptr; // Key not found.
- }
-
- const uint8_t *element = reinterpret_cast<const uint8_t *>(search_result);
-
- return IndirectHelper<T>::Read(element, 0);
- }
-
- protected:
- // This class is only used to access pre-existing data. Don't ever
- // try to construct these manually.
- Vector();
-
- uoffset_t length_;
-
- private:
- // This class is a pointer. Copying will therefore create an invalid object.
- // Private and unimplemented copy constructor.
- Vector(const Vector &);
- Vector &operator=(const Vector &);
-
- template<typename K> static int KeyCompare(const void *ap, const void *bp) {
- const K *key = reinterpret_cast<const K *>(ap);
- const uint8_t *data = reinterpret_cast<const uint8_t *>(bp);
- auto table = IndirectHelper<T>::Read(data, 0);
-
- // std::bsearch compares with the operands transposed, so we negate the
- // result here.
- return -table->KeyCompareWithValue(*key);
- }
-};
-
-// Represent a vector much like the template above, but in this case we
-// don't know what the element types are (used with reflection.h).
-class VectorOfAny {
- public:
- uoffset_t size() const { return EndianScalar(length_); }
-
- const uint8_t *Data() const {
- return reinterpret_cast<const uint8_t *>(&length_ + 1);
- }
- uint8_t *Data() { return reinterpret_cast<uint8_t *>(&length_ + 1); }
-
- protected:
- VectorOfAny();
-
- uoffset_t length_;
-
- private:
- VectorOfAny(const VectorOfAny &);
- VectorOfAny &operator=(const VectorOfAny &);
-};
-
-#ifndef FLATBUFFERS_CPP98_STL
-template<typename T, typename U>
-Vector<Offset<T>> *VectorCast(Vector<Offset<U>> *ptr) {
- static_assert(std::is_base_of<T, U>::value, "Unrelated types");
- return reinterpret_cast<Vector<Offset<T>> *>(ptr);
-}
-
-template<typename T, typename U>
-const Vector<Offset<T>> *VectorCast(const Vector<Offset<U>> *ptr) {
- static_assert(std::is_base_of<T, U>::value, "Unrelated types");
- return reinterpret_cast<const Vector<Offset<T>> *>(ptr);
-}
-#endif
-
-// Convenient helper function to get the length of any vector, regardless
-// of whether it is null or not (the field is not set).
-template<typename T> static inline size_t VectorLength(const Vector<T> *v) {
- return v ? v->size() : 0;
-}
-
-// This is used as a helper type for accessing arrays.
-template<typename T, uint16_t length> class Array {
- typedef
- typename flatbuffers::integral_constant<bool,
- flatbuffers::is_scalar<T>::value>
- scalar_tag;
- typedef
- typename flatbuffers::conditional<scalar_tag::value, T, const T *>::type
- IndirectHelperType;
-
- public:
- typedef uint16_t size_type;
- typedef typename IndirectHelper<IndirectHelperType>::return_type return_type;
- typedef VectorIterator<T, return_type> const_iterator;
- typedef VectorReverseIterator<const_iterator> const_reverse_iterator;
-
- FLATBUFFERS_CONSTEXPR uint16_t size() const { return length; }
-
- return_type Get(uoffset_t i) const {
- FLATBUFFERS_ASSERT(i < size());
- return IndirectHelper<IndirectHelperType>::Read(Data(), i);
- }
-
- return_type operator[](uoffset_t i) const { return Get(i); }
-
- // 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 E.
- template<typename E> E GetEnum(uoffset_t i) const {
- return static_cast<E>(Get(i));
- }
-
- const_iterator begin() const { return const_iterator(Data(), 0); }
- const_iterator end() const { return const_iterator(Data(), size()); }
-
- const_reverse_iterator rbegin() const {
- return const_reverse_iterator(end());
- }
- const_reverse_iterator rend() const { return const_reverse_iterator(end()); }
-
- const_iterator cbegin() const { return begin(); }
- const_iterator cend() const { return end(); }
-
- const_reverse_iterator crbegin() const { return rbegin(); }
- const_reverse_iterator crend() const { return rend(); }
-
- // Get a mutable pointer to elements inside this array.
- // This method used to mutate arrays of structs followed by a @p Mutate
- // operation. For primitive types use @p Mutate directly.
- // @warning Assignments and reads to/from the dereferenced pointer are not
- // automatically converted to the correct endianness.
- typename flatbuffers::conditional<scalar_tag::value, void, T *>::type
- GetMutablePointer(uoffset_t i) const {
- FLATBUFFERS_ASSERT(i < size());
- return const_cast<T *>(&data()[i]);
- }
-
- // Change elements if you have a non-const pointer to this object.
- void Mutate(uoffset_t i, const T &val) { MutateImpl(scalar_tag(), i, val); }
-
- // The raw data in little endian format. Use with care.
- const uint8_t *Data() const { return data_; }
-
- uint8_t *Data() { return data_; }
-
- // Similarly, but typed, much like std::vector::data
- const T *data() const { return reinterpret_cast<const T *>(Data()); }
- T *data() { return reinterpret_cast<T *>(Data()); }
-
- // Copy data from a span with endian conversion.
- // If this Array and the span overlap, the behavior is undefined.
- void CopyFromSpan(flatbuffers::span<const T, length> src) {
- const auto p1 = reinterpret_cast<const uint8_t *>(src.data());
- const auto p2 = Data();
- FLATBUFFERS_ASSERT(!(p1 >= p2 && p1 < (p2 + length)) &&
- !(p2 >= p1 && p2 < (p1 + length)));
- (void)p1;
- (void)p2;
-
- CopyFromSpanImpl(
- flatbuffers::integral_constant<bool,
- !scalar_tag::value || sizeof(T) == 1 || FLATBUFFERS_LITTLEENDIAN>(),
- src);
- }
-
- protected:
- void MutateImpl(flatbuffers::integral_constant<bool, true>, uoffset_t i,
- const T &val) {
- FLATBUFFERS_ASSERT(i < size());
- WriteScalar(data() + i, val);
- }
-
- void MutateImpl(flatbuffers::integral_constant<bool, false>, uoffset_t i,
- const T &val) {
- *(GetMutablePointer(i)) = val;
- }
-
- void CopyFromSpanImpl(flatbuffers::integral_constant<bool, true>,
- flatbuffers::span<const T, length> src) {
- // Use std::memcpy() instead of std::copy() to avoid preformance degradation
- // due to aliasing if T is char or unsigned char.
- // The size is known at compile time, so memcpy would be inlined.
- std::memcpy(data(), src.data(), length * sizeof(T));
- }
-
- // Copy data from flatbuffers::span with endian conversion.
- void CopyFromSpanImpl(flatbuffers::integral_constant<bool, false>,
- flatbuffers::span<const T, length> src) {
- for (size_type k = 0; k < length; k++) { Mutate(k, src[k]); }
- }
-
- // This class is only used to access pre-existing data. Don't ever
- // try to construct these manually.
- // 'constexpr' allows us to use 'size()' at compile time.
- // @note Must not use 'FLATBUFFERS_CONSTEXPR' here, as const is not allowed on
- // a constructor.
-#if defined(__cpp_constexpr)
- constexpr Array();
-#else
- Array();
-#endif
-
- uint8_t data_[length * sizeof(T)];
-
- private:
- // This class is a pointer. Copying will therefore create an invalid object.
- // Private and unimplemented copy constructor.
- Array(const Array &);
- Array &operator=(const Array &);
-};
-
-// Specialization for Array[struct] with access using Offset<void> pointer.
-// This specialization used by idl_gen_text.cpp.
-template<typename T, uint16_t length> class Array<Offset<T>, length> {
- static_assert(flatbuffers::is_same<T, void>::value, "unexpected type T");
-
- public:
- typedef const void *return_type;
-
- const uint8_t *Data() const { return data_; }
-
- // Make idl_gen_text.cpp::PrintContainer happy.
- return_type operator[](uoffset_t) const {
- FLATBUFFERS_ASSERT(false);
- return nullptr;
- }
-
- private:
- // This class is only used to access pre-existing data.
- Array();
- Array(const Array &);
- Array &operator=(const Array &);
-
- uint8_t data_[1];
-};
-
-// Cast a raw T[length] to a raw flatbuffers::Array<T, length>
-// without endian conversion. Use with care.
-template<typename T, uint16_t length>
-Array<T, length>& CastToArray(T (&arr)[length]) {
- return *reinterpret_cast<Array<T, length> *>(arr);
-}
-
-template<typename T, uint16_t length>
-const Array<T, length>& CastToArray(const T (&arr)[length]) {
- return *reinterpret_cast<const Array<T, length> *>(arr);
-}
-
-template<typename E, typename T, uint16_t length>
-Array<E, length> &CastToArrayOfEnum(T (&arr)[length]) {
- static_assert(sizeof(E) == sizeof(T), "invalid enum type E");
- return *reinterpret_cast<Array<E, length> *>(arr);
-}
-
-template<typename E, typename T, uint16_t length>
-const Array<E, length> &CastToArrayOfEnum(const T (&arr)[length]) {
- static_assert(sizeof(E) == sizeof(T), "invalid enum type E");
- return *reinterpret_cast<const Array<E, length> *>(arr);
-}
-
-// Lexicographically compare two strings (possibly containing nulls), and
-// return true if the first is less than the second.
-static inline bool StringLessThan(const char *a_data, uoffset_t a_size,
- const char *b_data, uoffset_t b_size) {
- const auto cmp = memcmp(a_data, b_data, (std::min)(a_size, b_size));
- return cmp == 0 ? a_size < b_size : cmp < 0;
-}
-
-struct String : public Vector<char> {
- const char *c_str() const { return reinterpret_cast<const char *>(Data()); }
- std::string str() const { return std::string(c_str(), size()); }
-
- // clang-format off
- #ifdef FLATBUFFERS_HAS_STRING_VIEW
- flatbuffers::string_view string_view() const {
- return flatbuffers::string_view(c_str(), size());
- }
- #endif // FLATBUFFERS_HAS_STRING_VIEW
- // clang-format on
-
- bool operator<(const String &o) const {
- return StringLessThan(this->data(), this->size(), o.data(), o.size());
- }
-};
-
-// Convenience function to get std::string from a String returning an empty
-// string on null pointer.
-static inline std::string GetString(const String *str) {
- return str ? str->str() : "";
-}
-
-// Convenience function to get char* from a String returning an empty string on
-// null pointer.
-static inline const char *GetCstring(const String *str) {
- return str ? str->c_str() : "";
-}
-
-#ifdef FLATBUFFERS_HAS_STRING_VIEW
-// Convenience function to get string_view from a String returning an empty
-// string_view on null pointer.
-static inline flatbuffers::string_view GetStringView(const String *str) {
- return str ? str->string_view() : flatbuffers::string_view();
-}
-#endif // FLATBUFFERS_HAS_STRING_VIEW
-
-// Allocator interface. This is flatbuffers-specific and meant only for
-// `vector_downward` usage.
-class Allocator {
- public:
- virtual ~Allocator() {}
-
- // Allocate `size` bytes of memory.
- virtual uint8_t *allocate(size_t size) = 0;
-
- // Deallocate `size` bytes of memory at `p` allocated by this allocator.
- virtual void deallocate(uint8_t *p, size_t size) = 0;
-
- // Reallocate `new_size` bytes of memory, replacing the old region of size
- // `old_size` at `p`. In contrast to a normal realloc, this grows downwards,
- // and is intended specifcally for `vector_downward` use.
- // `in_use_back` and `in_use_front` indicate how much of `old_size` is
- // actually in use at each end, and needs to be copied.
- virtual uint8_t *reallocate_downward(uint8_t *old_p, size_t old_size,
- size_t new_size, size_t in_use_back,
- size_t in_use_front) {
- FLATBUFFERS_ASSERT(new_size > old_size); // vector_downward only grows
- uint8_t *new_p = allocate(new_size);
- memcpy_downward(old_p, old_size, new_p, new_size, in_use_back,
- in_use_front);
- deallocate(old_p, old_size);
- return new_p;
- }
-
- protected:
- // Called by `reallocate_downward` to copy memory from `old_p` of `old_size`
- // to `new_p` of `new_size`. Only memory of size `in_use_front` and
- // `in_use_back` will be copied from the front and back of the old memory
- // allocation.
- void memcpy_downward(uint8_t *old_p, size_t old_size, uint8_t *new_p,
- size_t new_size, size_t in_use_back,
- size_t in_use_front) {
- memcpy(new_p + new_size - in_use_back, old_p + old_size - in_use_back,
- in_use_back);
- memcpy(new_p, old_p, in_use_front);
- }
-};
-
-// DefaultAllocator uses new/delete to allocate memory regions
-class DefaultAllocator : public Allocator {
- public:
- uint8_t *allocate(size_t size) FLATBUFFERS_OVERRIDE {
- return new uint8_t[size];
- }
-
- void deallocate(uint8_t *p, size_t) FLATBUFFERS_OVERRIDE { delete[] p; }
-
- static void dealloc(void *p, size_t) { delete[] static_cast<uint8_t *>(p); }
-};
-
-// These functions allow for a null allocator to mean use the default allocator,
-// as used by DetachedBuffer and vector_downward below.
-// This is to avoid having a statically or dynamically allocated default
-// allocator, or having to move it between the classes that may own it.
-inline uint8_t *Allocate(Allocator *allocator, size_t size) {
- return allocator ? allocator->allocate(size)
- : DefaultAllocator().allocate(size);
-}
-
-inline void Deallocate(Allocator *allocator, uint8_t *p, size_t size) {
- if (allocator)
- allocator->deallocate(p, size);
- else
- DefaultAllocator().deallocate(p, size);
-}
-
-inline uint8_t *ReallocateDownward(Allocator *allocator, uint8_t *old_p,
- size_t old_size, size_t new_size,
- size_t in_use_back, size_t in_use_front) {
- return allocator ? allocator->reallocate_downward(old_p, old_size, new_size,
- in_use_back, in_use_front)
- : DefaultAllocator().reallocate_downward(
- old_p, old_size, new_size, in_use_back, in_use_front);
-}
-
-// DetachedBuffer is a finished flatbuffer memory region, detached from its
-// builder. The original memory region and allocator are also stored so that
-// the DetachedBuffer can manage the memory lifetime.
-class DetachedBuffer {
- public:
- DetachedBuffer()
- : allocator_(nullptr),
- own_allocator_(false),
- buf_(nullptr),
- reserved_(0),
- cur_(nullptr),
- size_(0) {}
-
- DetachedBuffer(Allocator *allocator, bool own_allocator, uint8_t *buf,
- size_t reserved, uint8_t *cur, size_t sz)
- : allocator_(allocator),
- own_allocator_(own_allocator),
- buf_(buf),
- reserved_(reserved),
- cur_(cur),
- size_(sz) {}
-
- // clang-format off
- #if !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
- DetachedBuffer(DetachedBuffer &&other)
- : allocator_(other.allocator_),
- own_allocator_(other.own_allocator_),
- buf_(other.buf_),
- reserved_(other.reserved_),
- cur_(other.cur_),
- size_(other.size_) {
- other.reset();
- }
- // clang-format off
- #endif // !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
-
- // clang-format off
- #if !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
- DetachedBuffer &operator=(DetachedBuffer &&other) {
- if (this == &other) return *this;
-
- destroy();
-
- allocator_ = other.allocator_;
- own_allocator_ = other.own_allocator_;
- buf_ = other.buf_;
- reserved_ = other.reserved_;
- cur_ = other.cur_;
- size_ = other.size_;
-
- other.reset();
-
- return *this;
- }
- // clang-format off
- #endif // !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
-
- ~DetachedBuffer() { destroy(); }
-
- const uint8_t *data() const { return cur_; }
-
- uint8_t *data() { return cur_; }
-
- size_t size() const { return size_; }
-
- // clang-format off
- #if 0 // disabled for now due to the ordering of classes in this header
- template <class T>
- bool Verify() const {
- Verifier verifier(data(), size());
- return verifier.Verify<T>(nullptr);
- }
-
- template <class T>
- const T* GetRoot() const {
- return flatbuffers::GetRoot<T>(data());
- }
-
- template <class T>
- T* GetRoot() {
- return flatbuffers::GetRoot<T>(data());
- }
- #endif
- // clang-format on
-
- // clang-format off
- #if !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
- // These may change access mode, leave these at end of public section
- FLATBUFFERS_DELETE_FUNC(DetachedBuffer(const DetachedBuffer &other))
- FLATBUFFERS_DELETE_FUNC(
- DetachedBuffer &operator=(const DetachedBuffer &other))
- // clang-format off
- #endif // !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
-
- protected:
- Allocator *allocator_;
- bool own_allocator_;
- uint8_t *buf_;
- size_t reserved_;
- uint8_t *cur_;
- size_t size_;
-
- inline void destroy() {
- if (buf_) Deallocate(allocator_, buf_, reserved_);
- if (own_allocator_ && allocator_) { delete allocator_; }
- reset();
- }
-
- inline void reset() {
- allocator_ = nullptr;
- own_allocator_ = false;
- buf_ = nullptr;
- reserved_ = 0;
- cur_ = nullptr;
- size_ = 0;
- }
-};
-
-// This is a minimal replication of std::vector<uint8_t> functionality,
-// except growing from higher to lower addresses. i.e push_back() inserts data
-// in the lowest address in the vector.
-// 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.
-// Essentially, this supports 2 std::vectors in a single buffer.
-class vector_downward {
- public:
- explicit vector_downward(size_t initial_size, Allocator *allocator,
- bool own_allocator, size_t buffer_minalign)
- : allocator_(allocator),
- own_allocator_(own_allocator),
- initial_size_(initial_size),
- buffer_minalign_(buffer_minalign),
- reserved_(0),
- buf_(nullptr),
- cur_(nullptr),
- scratch_(nullptr) {}
-
- // clang-format off
- #if !defined(FLATBUFFERS_CPP98_STL)
- vector_downward(vector_downward &&other)
- #else
- vector_downward(vector_downward &other)
- #endif // defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
- : allocator_(other.allocator_),
- own_allocator_(other.own_allocator_),
- initial_size_(other.initial_size_),
- buffer_minalign_(other.buffer_minalign_),
- reserved_(other.reserved_),
- buf_(other.buf_),
- cur_(other.cur_),
- scratch_(other.scratch_) {
- // No change in other.allocator_
- // No change in other.initial_size_
- // No change in other.buffer_minalign_
- other.own_allocator_ = false;
- other.reserved_ = 0;
- other.buf_ = nullptr;
- other.cur_ = nullptr;
- other.scratch_ = nullptr;
- }
-
- // clang-format off
- #if !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
- vector_downward &operator=(vector_downward &&other) {
- // Move construct a temporary and swap idiom
- vector_downward temp(std::move(other));
- swap(temp);
- return *this;
- }
- // clang-format off
- #endif // defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
-
- ~vector_downward() {
- clear_buffer();
- clear_allocator();
- }
-
- void reset() {
- clear_buffer();
- clear();
- }
-
- void clear() {
- if (buf_) {
- cur_ = buf_ + reserved_;
- } else {
- reserved_ = 0;
- cur_ = nullptr;
- }
- clear_scratch();
- }
-
- void clear_scratch() { scratch_ = buf_; }
-
- void clear_allocator() {
- if (own_allocator_ && allocator_) { delete allocator_; }
- allocator_ = nullptr;
- own_allocator_ = false;
- }
-
- void clear_buffer() {
- if (buf_) Deallocate(allocator_, buf_, reserved_);
- buf_ = nullptr;
- }
-
- // Relinquish the pointer to the caller.
- uint8_t *release_raw(size_t &allocated_bytes, size_t &offset) {
- auto *buf = buf_;
- allocated_bytes = reserved_;
- offset = static_cast<size_t>(cur_ - buf_);
-
- // release_raw only relinquishes the buffer ownership.
- // Does not deallocate or reset the allocator. Destructor will do that.
- buf_ = nullptr;
- clear();
- return buf;
- }
-
- // Relinquish the pointer to the caller.
- DetachedBuffer release() {
- // allocator ownership (if any) is transferred to DetachedBuffer.
- DetachedBuffer fb(allocator_, own_allocator_, buf_, reserved_, cur_,
- size());
- if (own_allocator_) {
- allocator_ = nullptr;
- own_allocator_ = false;
- }
- buf_ = nullptr;
- clear();
- return fb;
- }
-
- size_t ensure_space(size_t len) {
- FLATBUFFERS_ASSERT(cur_ >= scratch_ && scratch_ >= buf_);
- if (len > static_cast<size_t>(cur_ - scratch_)) { reallocate(len); }
- // Beyond this, signed offsets may not have enough range:
- // (FlatBuffers > 2GB not supported).
- FLATBUFFERS_ASSERT(size() < FLATBUFFERS_MAX_BUFFER_SIZE);
- return len;
- }
-
- inline uint8_t *make_space(size_t len) {
- size_t space = ensure_space(len);
- cur_ -= space;
- return cur_;
- }
-
- // Returns nullptr if using the DefaultAllocator.
- Allocator *get_custom_allocator() { return allocator_; }
-
- uoffset_t size() const {
- return static_cast<uoffset_t>(reserved_ - static_cast<size_t>(cur_ - buf_));
- }
-
- uoffset_t scratch_size() const {
- return static_cast<uoffset_t>(scratch_ - buf_);
- }
-
- size_t capacity() const { return reserved_; }
-
- uint8_t *data() const {
- FLATBUFFERS_ASSERT(cur_);
- return cur_;
- }
-
- uint8_t *scratch_data() const {
- FLATBUFFERS_ASSERT(buf_);
- return buf_;
- }
-
- uint8_t *scratch_end() const {
- FLATBUFFERS_ASSERT(scratch_);
- return scratch_;
- }
-
- uint8_t *data_at(size_t offset) const { return buf_ + reserved_ - offset; }
-
- void push(const uint8_t *bytes, size_t num) {
- if (num > 0) { memcpy(make_space(num), bytes, num); }
- }
-
- // Specialized version of push() that avoids memcpy call for small data.
- template<typename T> void push_small(const T &little_endian_t) {
- make_space(sizeof(T));
- *reinterpret_cast<T *>(cur_) = little_endian_t;
- }
-
- template<typename T> void scratch_push_small(const T &t) {
- ensure_space(sizeof(T));
- *reinterpret_cast<T *>(scratch_) = t;
- scratch_ += sizeof(T);
- }
-
- // fill() is most frequently called with small byte counts (<= 4),
- // which is why we're using loops rather than calling memset.
- void fill(size_t zero_pad_bytes) {
- make_space(zero_pad_bytes);
- for (size_t i = 0; i < zero_pad_bytes; i++) cur_[i] = 0;
- }
-
- // Version for when we know the size is larger.
- // Precondition: zero_pad_bytes > 0
- void fill_big(size_t zero_pad_bytes) {
- memset(make_space(zero_pad_bytes), 0, zero_pad_bytes);
- }
-
- void pop(size_t bytes_to_remove) { cur_ += bytes_to_remove; }
- void scratch_pop(size_t bytes_to_remove) { scratch_ -= bytes_to_remove; }
-
- void swap(vector_downward &other) {
- using std::swap;
- swap(allocator_, other.allocator_);
- swap(own_allocator_, other.own_allocator_);
- swap(initial_size_, other.initial_size_);
- swap(buffer_minalign_, other.buffer_minalign_);
- swap(reserved_, other.reserved_);
- swap(buf_, other.buf_);
- swap(cur_, other.cur_);
- swap(scratch_, other.scratch_);
- }
-
- void swap_allocator(vector_downward &other) {
- using std::swap;
- swap(allocator_, other.allocator_);
- swap(own_allocator_, other.own_allocator_);
- }
-
- private:
- // You shouldn't really be copying instances of this class.
- FLATBUFFERS_DELETE_FUNC(vector_downward(const vector_downward &))
- FLATBUFFERS_DELETE_FUNC(vector_downward &operator=(const vector_downward &))
-
- Allocator *allocator_;
- bool own_allocator_;
- size_t initial_size_;
- size_t buffer_minalign_;
- size_t reserved_;
- uint8_t *buf_;
- uint8_t *cur_; // Points at location between empty (below) and used (above).
- uint8_t *scratch_; // Points to the end of the scratchpad in use.
-
- void reallocate(size_t len) {
- auto old_reserved = reserved_;
- auto old_size = size();
- auto old_scratch_size = scratch_size();
- reserved_ +=
- (std::max)(len, old_reserved ? old_reserved / 2 : initial_size_);
- reserved_ = (reserved_ + buffer_minalign_ - 1) & ~(buffer_minalign_ - 1);
- if (buf_) {
- buf_ = ReallocateDownward(allocator_, buf_, old_reserved, reserved_,
- old_size, old_scratch_size);
- } else {
- buf_ = Allocate(allocator_, reserved_);
- }
- cur_ = buf_ + reserved_ - old_size;
- scratch_ = buf_ + old_scratch_size;
- }
-};
-
-// Converts a Field ID to a virtual table offset.
-inline voffset_t FieldIndexToOffset(voffset_t field_id) {
- // Should correspond to what EndTable() below builds up.
- const int fixed_fields = 2; // Vtable size and Object Size.
- return static_cast<voffset_t>((field_id + fixed_fields) * sizeof(voffset_t));
-}
-
-template<typename T, typename Alloc>
-const T *data(const std::vector<T, Alloc> &v) {
- // Eventually the returned pointer gets passed down to memcpy, so
- // we need it to be non-null to avoid undefined behavior.
- static uint8_t t;
- return v.empty() ? reinterpret_cast<const T *>(&t) : &v.front();
-}
-template<typename T, typename Alloc> T *data(std::vector<T, Alloc> &v) {
- // Eventually the returned pointer gets passed down to memcpy, so
- // we need it to be non-null to avoid undefined behavior.
- static uint8_t t;
- return v.empty() ? reinterpret_cast<T *>(&t) : &v.front();
-}
-
-/// @endcond
-
-/// @addtogroup flatbuffers_cpp_api
-/// @{
-/// @class FlatBufferBuilder
-/// @brief Helper class to hold data needed in creation of a FlatBuffer.
-/// To serialize data, you typically call one of the `Create*()` functions in
-/// the generated code, which in turn call a sequence of `StartTable`/
-/// `PushElement`/`AddElement`/`EndTable`, or the builtin `CreateString`/
-/// `CreateVector` functions. Do this is depth-first order to build up a tree to
-/// the root. `Finish()` wraps up the buffer ready for transport.
-class FlatBufferBuilder {
- public:
- /// @brief Default constructor for FlatBufferBuilder.
- /// @param[in] initial_size The initial size of the buffer, in bytes. Defaults
- /// to `1024`.
- /// @param[in] allocator An `Allocator` to use. If null will use
- /// `DefaultAllocator`.
- /// @param[in] own_allocator Whether the builder/vector should own the
- /// allocator. Defaults to / `false`.
- /// @param[in] buffer_minalign Force the buffer to be aligned to the given
- /// minimum alignment upon reallocation. Only needed if you intend to store
- /// types with custom alignment AND you wish to read the buffer in-place
- /// directly after creation.
- explicit FlatBufferBuilder(
- size_t initial_size = 1024, Allocator *allocator = nullptr,
- bool own_allocator = false,
- size_t buffer_minalign = AlignOf<largest_scalar_t>())
- : buf_(initial_size, allocator, own_allocator, buffer_minalign),
- num_field_loc(0),
- max_voffset_(0),
- nested(false),
- finished(false),
- minalign_(1),
- force_defaults_(false),
- dedup_vtables_(true),
- string_pool(nullptr) {
- EndianCheck();
- }
-
- // clang-format off
- /// @brief Move constructor for FlatBufferBuilder.
- #if !defined(FLATBUFFERS_CPP98_STL)
- FlatBufferBuilder(FlatBufferBuilder &&other)
- #else
- FlatBufferBuilder(FlatBufferBuilder &other)
- #endif // #if !defined(FLATBUFFERS_CPP98_STL)
- : buf_(1024, nullptr, false, AlignOf<largest_scalar_t>()),
- num_field_loc(0),
- max_voffset_(0),
- nested(false),
- finished(false),
- minalign_(1),
- force_defaults_(false),
- dedup_vtables_(true),
- string_pool(nullptr) {
- EndianCheck();
- // Default construct and swap idiom.
- // Lack of delegating constructors in vs2010 makes it more verbose than needed.
- Swap(other);
- }
- // clang-format on
-
- // clang-format off
- #if !defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
- /// @brief Move assignment operator for FlatBufferBuilder.
- FlatBufferBuilder &operator=(FlatBufferBuilder &&other) {
- // Move construct a temporary and swap idiom
- FlatBufferBuilder temp(std::move(other));
- Swap(temp);
- return *this;
- }
- // clang-format off
- #endif // defined(FLATBUFFERS_CPP98_STL)
- // clang-format on
-
- void Swap(FlatBufferBuilder &other) {
- using std::swap;
- buf_.swap(other.buf_);
- swap(num_field_loc, other.num_field_loc);
- swap(max_voffset_, other.max_voffset_);
- swap(nested, other.nested);
- swap(finished, other.finished);
- swap(minalign_, other.minalign_);
- swap(force_defaults_, other.force_defaults_);
- swap(dedup_vtables_, other.dedup_vtables_);
- swap(string_pool, other.string_pool);
- }
-
- ~FlatBufferBuilder() {
- if (string_pool) delete string_pool;
- }
-
- void Reset() {
- Clear(); // clear builder state
- buf_.reset(); // deallocate buffer
- }
-
- /// @brief Reset all the state in this FlatBufferBuilder so it can be reused
- /// to construct another buffer.
- void Clear() {
- ClearOffsets();
- buf_.clear();
- nested = false;
- finished = false;
- minalign_ = 1;
- if (string_pool) string_pool->clear();
- }
-
- /// @brief The current size of the serialized buffer, counting from the end.
- /// @return Returns an `uoffset_t` with the current size of the buffer.
- uoffset_t GetSize() const { return buf_.size(); }
-
- /// @brief Get the serialized buffer (after you call `Finish()`).
- /// @return Returns an `uint8_t` pointer to the FlatBuffer data inside the
- /// buffer.
- uint8_t *GetBufferPointer() const {
- Finished();
- return buf_.data();
- }
-
- /// @brief Get the serialized buffer (after you call `Finish()`) as a span.
- /// @return Returns a constructed flatbuffers::span that is a view over the
- /// FlatBuffer data inside the buffer.
- flatbuffers::span<uint8_t> GetBufferSpan() const {
- Finished();
- return flatbuffers::span<uint8_t>(buf_.data(), buf_.size());
- }
-
- /// @brief Get a pointer to an unfinished buffer.
- /// @return Returns a `uint8_t` pointer to the unfinished buffer.
- uint8_t *GetCurrentBufferPointer() const { return buf_.data(); }
-
- /// @brief Get the released pointer to the serialized buffer.
- /// @warning Do NOT attempt to use this FlatBufferBuilder afterwards!
- /// @return A `FlatBuffer` that owns the buffer and its allocator and
- /// behaves similar to a `unique_ptr` with a deleter.
- FLATBUFFERS_ATTRIBUTE(deprecated("use Release() instead"))
- DetachedBuffer ReleaseBufferPointer() {
- Finished();
- return buf_.release();
- }
-
- /// @brief Get the released DetachedBuffer.
- /// @return A `DetachedBuffer` that owns the buffer and its allocator.
- DetachedBuffer Release() {
- Finished();
- return buf_.release();
- }
-
- /// @brief Get the released pointer to the serialized buffer.
- /// @param size The size of the memory block containing
- /// the serialized `FlatBuffer`.
- /// @param offset The offset from the released pointer where the finished
- /// `FlatBuffer` starts.
- /// @return A raw pointer to the start of the memory block containing
- /// the serialized `FlatBuffer`.
- /// @remark If the allocator is owned, it gets deleted when the destructor is
- /// called..
- uint8_t *ReleaseRaw(size_t &size, size_t &offset) {
- Finished();
- return buf_.release_raw(size, offset);
- }
-
- /// @brief get the minimum alignment this buffer needs to be accessed
- /// properly. This is only known once all elements have been written (after
- /// you call Finish()). You can use this information if you need to embed
- /// a FlatBuffer in some other buffer, such that you can later read it
- /// without first having to copy it into its own buffer.
- size_t GetBufferMinAlignment() const {
- Finished();
- return minalign_;
- }
-
- /// @cond FLATBUFFERS_INTERNAL
- void Finished() const {
- // If you get this assert, you're attempting to get access a buffer
- // which hasn't been finished yet. Be sure to call
- // FlatBufferBuilder::Finish with your root table.
- // If you really need to access an unfinished buffer, call
- // GetCurrentBufferPointer instead.
- FLATBUFFERS_ASSERT(finished);
- }
- /// @endcond
-
- /// @brief In order to save space, fields that are set to their default value
- /// don't get serialized into the buffer.
- /// @param[in] fd When set to `true`, always serializes default values that
- /// are set. Optional fields which are not set explicitly, will still not be
- /// serialized.
- void ForceDefaults(bool fd) { force_defaults_ = fd; }
-
- /// @brief By default vtables are deduped in order to save space.
- /// @param[in] dedup When set to `true`, dedup vtables.
- void DedupVtables(bool dedup) { dedup_vtables_ = dedup; }
-
- /// @cond FLATBUFFERS_INTERNAL
- void Pad(size_t num_bytes) { buf_.fill(num_bytes); }
-
- void TrackMinAlign(size_t elem_size) {
- if (elem_size > minalign_) minalign_ = elem_size;
- }
-
- void Align(size_t elem_size) {
- TrackMinAlign(elem_size);
- buf_.fill(PaddingBytes(buf_.size(), elem_size));
- }
-
- void PushFlatBuffer(const uint8_t *bytes, size_t size) {
- PushBytes(bytes, size);
- finished = true;
- }
-
- void PushBytes(const uint8_t *bytes, size_t size) { buf_.push(bytes, size); }
-
- void PopBytes(size_t amount) { buf_.pop(amount); }
-
- template<typename T> void AssertScalarT() {
- // The code assumes power of 2 sizes and endian-swap-ability.
- static_assert(flatbuffers::is_scalar<T>::value, "T must be a scalar type");
- }
-
- // Write a single aligned scalar to the buffer
- template<typename T> uoffset_t PushElement(T element) {
- AssertScalarT<T>();
- T litle_endian_element = EndianScalar(element);
- Align(sizeof(T));
- buf_.push_small(litle_endian_element);
- return GetSize();
- }
-
- template<typename T> uoffset_t PushElement(Offset<T> off) {
- // Special case for offsets: see ReferTo below.
- return PushElement(ReferTo(off.o));
- }
-
- // When writing fields, we track where they are, so we can create correct
- // vtables later.
- void TrackField(voffset_t field, uoffset_t off) {
- FieldLoc fl = { off, field };
- buf_.scratch_push_small(fl);
- num_field_loc++;
- max_voffset_ = (std::max)(max_voffset_, field);
- }
-
- // Like PushElement, but additionally tracks the field this represents.
- template<typename T> void AddElement(voffset_t field, T e, T def) {
- // We don't serialize values equal to the default.
- if (IsTheSameAs(e, def) && !force_defaults_) return;
- auto off = PushElement(e);
- TrackField(field, off);
- }
-
- template<typename T> void AddElement(voffset_t field, T e) {
- auto off = PushElement(e);
- TrackField(field, off);
- }
-
- template<typename T> void AddOffset(voffset_t field, Offset<T> off) {
- if (off.IsNull()) return; // Don't store.
- AddElement(field, ReferTo(off.o), static_cast<uoffset_t>(0));
- }
-
- template<typename T> void AddStruct(voffset_t field, const T *structptr) {
- if (!structptr) return; // Default, don't store.
- Align(AlignOf<T>());
- buf_.push_small(*structptr);
- TrackField(field, GetSize());
- }
-
- void AddStructOffset(voffset_t field, uoffset_t off) {
- TrackField(field, off);
- }
-
- // Offsets initially are relative to the end of the buffer (downwards).
- // This function converts them to be relative to the current location
- // in the buffer (when stored here), pointing upwards.
- uoffset_t ReferTo(uoffset_t off) {
- // Align to ensure GetSize() below is correct.
- Align(sizeof(uoffset_t));
- // Offset must refer to something already in buffer.
- FLATBUFFERS_ASSERT(off && off <= GetSize());
- return GetSize() - off + static_cast<uoffset_t>(sizeof(uoffset_t));
- }
-
- void NotNested() {
- // If you hit this, you're trying to construct a Table/Vector/String
- // during the construction of its parent table (between the MyTableBuilder
- // and table.Finish().
- // Move the creation of these sub-objects to above the MyTableBuilder to
- // not get this assert.
- // Ignoring this assert may appear to work in simple cases, but the reason
- // it is here is that storing objects in-line may cause vtable offsets
- // to not fit anymore. It also leads to vtable duplication.
- FLATBUFFERS_ASSERT(!nested);
- // If you hit this, fields were added outside the scope of a table.
- FLATBUFFERS_ASSERT(!num_field_loc);
- }
-
- // From generated code (or from the parser), we call StartTable/EndTable
- // with a sequence of AddElement calls in between.
- uoffset_t StartTable() {
- NotNested();
- nested = true;
- return GetSize();
- }
-
- // This finishes one serialized object by generating the vtable if it's a
- // table, comparing it against existing vtables, and writing the
- // resulting vtable offset.
- uoffset_t EndTable(uoffset_t start) {
- // If you get this assert, a corresponding StartTable wasn't called.
- FLATBUFFERS_ASSERT(nested);
- // Write the vtable offset, which is the start of any Table.
- // We fill it's value later.
- auto vtableoffsetloc = PushElement<soffset_t>(0);
- // Write a vtable, which consists entirely of voffset_t elements.
- // It starts with the number of offsets, followed by a type id, followed
- // by the offsets themselves. In reverse:
- // Include space for the last offset and ensure empty tables have a
- // minimum size.
- max_voffset_ =
- (std::max)(static_cast<voffset_t>(max_voffset_ + sizeof(voffset_t)),
- FieldIndexToOffset(0));
- buf_.fill_big(max_voffset_);
- auto table_object_size = vtableoffsetloc - start;
- // Vtable use 16bit offsets.
- FLATBUFFERS_ASSERT(table_object_size < 0x10000);
- WriteScalar<voffset_t>(buf_.data() + sizeof(voffset_t),
- static_cast<voffset_t>(table_object_size));
- WriteScalar<voffset_t>(buf_.data(), max_voffset_);
- // Write the offsets into the table
- for (auto it = buf_.scratch_end() - num_field_loc * sizeof(FieldLoc);
- it < buf_.scratch_end(); it += sizeof(FieldLoc)) {
- auto field_location = reinterpret_cast<FieldLoc *>(it);
- auto pos = static_cast<voffset_t>(vtableoffsetloc - field_location->off);
- // If this asserts, it means you've set a field twice.
- FLATBUFFERS_ASSERT(
- !ReadScalar<voffset_t>(buf_.data() + field_location->id));
- WriteScalar<voffset_t>(buf_.data() + field_location->id, pos);
- }
- ClearOffsets();
- auto vt1 = reinterpret_cast<voffset_t *>(buf_.data());
- auto vt1_size = ReadScalar<voffset_t>(vt1);
- auto vt_use = GetSize();
- // See if we already have generated a vtable with this exact same
- // layout before. If so, make it point to the old one, remove this one.
- if (dedup_vtables_) {
- for (auto it = buf_.scratch_data(); it < buf_.scratch_end();
- it += sizeof(uoffset_t)) {
- auto vt_offset_ptr = reinterpret_cast<uoffset_t *>(it);
- auto vt2 = reinterpret_cast<voffset_t *>(buf_.data_at(*vt_offset_ptr));
- auto vt2_size = ReadScalar<voffset_t>(vt2);
- if (vt1_size != vt2_size || 0 != memcmp(vt2, vt1, vt1_size)) continue;
- vt_use = *vt_offset_ptr;
- buf_.pop(GetSize() - vtableoffsetloc);
- break;
- }
- }
- // If this is a new vtable, remember it.
- if (vt_use == GetSize()) { buf_.scratch_push_small(vt_use); }
- // Fill the vtable offset we created above.
- // The offset points from the beginning of the object to where the
- // vtable is stored.
- // Offsets default direction is downward in memory for future format
- // flexibility (storing all vtables at the start of the file).
- WriteScalar(buf_.data_at(vtableoffsetloc),
- static_cast<soffset_t>(vt_use) -
- static_cast<soffset_t>(vtableoffsetloc));
-
- nested = false;
- return vtableoffsetloc;
- }
-
- FLATBUFFERS_ATTRIBUTE(deprecated("call the version above instead"))
- uoffset_t EndTable(uoffset_t start, voffset_t /*numfields*/) {
- return EndTable(start);
- }
-
- // This checks a required field has been set in a given table that has
- // just been constructed.
- template<typename T> void Required(Offset<T> table, voffset_t field);
-
- uoffset_t StartStruct(size_t alignment) {
- Align(alignment);
- return GetSize();
- }
-
- uoffset_t EndStruct() { return GetSize(); }
-
- void ClearOffsets() {
- buf_.scratch_pop(num_field_loc * sizeof(FieldLoc));
- num_field_loc = 0;
- max_voffset_ = 0;
- }
-
- // Aligns such that when "len" bytes are written, an object can be written
- // after it with "alignment" without padding.
- void PreAlign(size_t len, size_t alignment) {
- TrackMinAlign(alignment);
- buf_.fill(PaddingBytes(GetSize() + len, alignment));
- }
- template<typename T> void PreAlign(size_t len) {
- AssertScalarT<T>();
- PreAlign(len, sizeof(T));
- }
- /// @endcond
-
- /// @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.
- Offset<String> CreateString(const char *str, size_t len) {
- NotNested();
- PreAlign<uoffset_t>(len + 1); // Always 0-terminated.
- buf_.fill(1);
- PushBytes(reinterpret_cast<const uint8_t *>(str), len);
- PushElement(static_cast<uoffset_t>(len));
- return Offset<String>(GetSize());
- }
-
- /// @brief Store a string in the buffer, which is null-terminated.
- /// @param[in] str A const char pointer to a C-string to add to the buffer.
- /// @return Returns the offset in the buffer where the string starts.
- Offset<String> CreateString(const char *str) {
- return CreateString(str, strlen(str));
- }
-
- /// @brief Store a string in the buffer, which is null-terminated.
- /// @param[in] str A char pointer to a C-string to add to the buffer.
- /// @return Returns the offset in the buffer where the string starts.
- Offset<String> CreateString(char *str) {
- return CreateString(str, strlen(str));
- }
-
- /// @brief Store a string in the buffer, which can contain any binary data.
- /// @param[in] str A const reference to a std::string to store in the buffer.
- /// @return Returns the offset in the buffer where the string starts.
- Offset<String> CreateString(const std::string &str) {
- return CreateString(str.c_str(), str.length());
- }
-
- // clang-format off
- #ifdef FLATBUFFERS_HAS_STRING_VIEW
- /// @brief Store a string in the buffer, which can contain any binary data.
- /// @param[in] str A const string_view to copy in to the buffer.
- /// @return Returns the offset in the buffer where the string starts.
- Offset<String> CreateString(flatbuffers::string_view str) {
- return CreateString(str.data(), str.size());
- }
- #endif // FLATBUFFERS_HAS_STRING_VIEW
- // clang-format on
-
- /// @brief Store a string in the buffer, which can contain any binary data.
- /// @param[in] str A const pointer to a `String` struct to add to the buffer.
- /// @return Returns the offset in the buffer where the string starts
- Offset<String> CreateString(const String *str) {
- return str ? CreateString(str->c_str(), str->size()) : 0;
- }
-
- /// @brief Store a string in the buffer, which can contain any binary data.
- /// @param[in] str A const reference to a std::string like type with support
- /// of T::c_str() and T::length() to store in the buffer.
- /// @return Returns the offset in the buffer where the string starts.
- template<typename T> Offset<String> CreateString(const T &str) {
- return CreateString(str.c_str(), str.length());
- }
-
- /// @brief Store a string in the buffer, which can contain any binary data.
- /// If a string with this exact contents has already been serialized before,
- /// instead simply returns the offset of the existing 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`.
- /// @return Returns the offset in the buffer where the string starts.
- Offset<String> CreateSharedString(const char *str, size_t len) {
- if (!string_pool)
- string_pool = new StringOffsetMap(StringOffsetCompare(buf_));
- auto size_before_string = buf_.size();
- // Must first serialize the string, since the set is all offsets into
- // buffer.
- auto off = CreateString(str, len);
- auto it = string_pool->find(off);
- // If it exists we reuse existing serialized data!
- if (it != string_pool->end()) {
- // We can remove the string we serialized.
- buf_.pop(buf_.size() - size_before_string);
- return *it;
- }
- // Record this string for future use.
- string_pool->insert(off);
- return off;
- }
-
- /// @brief Store a string in the buffer, which null-terminated.
- /// If a string with this exact contents has already been serialized before,
- /// instead simply returns the offset of the existing string.
- /// @param[in] str A const char pointer to a C-string to add to the buffer.
- /// @return Returns the offset in the buffer where the string starts.
- Offset<String> CreateSharedString(const char *str) {
- return CreateSharedString(str, strlen(str));
- }
-
- /// @brief Store a string in the buffer, which can contain any binary data.
- /// If a string with this exact contents has already been serialized before,
- /// instead simply returns the offset of the existing string.
- /// @param[in] str A const reference to a std::string to store in the buffer.
- /// @return Returns the offset in the buffer where the string starts.
- Offset<String> CreateSharedString(const std::string &str) {
- return CreateSharedString(str.c_str(), str.length());
- }
-
- /// @brief Store a string in the buffer, which can contain any binary data.
- /// If a string with this exact contents has already been serialized before,
- /// instead simply returns the offset of the existing string.
- /// @param[in] str A const pointer to a `String` struct to add to the buffer.
- /// @return Returns the offset in the buffer where the string starts
- Offset<String> CreateSharedString(const String *str) {
- return CreateSharedString(str->c_str(), str->size());
- }
-
- /// @cond FLATBUFFERS_INTERNAL
- uoffset_t EndVector(size_t len) {
- FLATBUFFERS_ASSERT(nested); // Hit if no corresponding StartVector.
- nested = false;
- return PushElement(static_cast<uoffset_t>(len));
- }
-
- void StartVector(size_t len, size_t elemsize) {
- NotNested();
- nested = true;
- PreAlign<uoffset_t>(len * elemsize);
- PreAlign(len * elemsize, elemsize); // Just in case elemsize > uoffset_t.
- }
-
- // Call this right before StartVector/CreateVector if you want to force the
- // alignment to be something different than what the element size would
- // normally dictate.
- // This is useful when storing a nested_flatbuffer in a vector of bytes,
- // or when storing SIMD floats, etc.
- void ForceVectorAlignment(size_t len, size_t elemsize, size_t alignment) {
- PreAlign(len * elemsize, alignment);
- }
-
- // Similar to ForceVectorAlignment but for String fields.
- void ForceStringAlignment(size_t len, size_t alignment) {
- PreAlign((len + 1) * sizeof(char), alignment);
- }
-
- /// @endcond
-
- /// @brief Serialize an array into a FlatBuffer `vector`.
- /// @tparam T The data type of the array elements.
- /// @param[in] v A pointer to the array of type `T` to serialize into the
- /// buffer as a `vector`.
- /// @param[in] len The number of elements to serialize.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- template<typename T> Offset<Vector<T>> CreateVector(const T *v, size_t len) {
- // If this assert hits, you're specifying a template argument that is
- // causing the wrong overload to be selected, remove it.
- AssertScalarT<T>();
- StartVector(len, sizeof(T));
- if (len == 0) {
- return Offset<Vector<T>>(EndVector(len));
- }
- // clang-format off
- #if FLATBUFFERS_LITTLEENDIAN
- PushBytes(reinterpret_cast<const uint8_t *>(v), len * sizeof(T));
- #else
- if (sizeof(T) == 1) {
- PushBytes(reinterpret_cast<const uint8_t *>(v), len);
- } else {
- for (auto i = len; i > 0; ) {
- PushElement(v[--i]);
- }
- }
- #endif
- // clang-format on
- return Offset<Vector<T>>(EndVector(len));
- }
-
- template<typename T>
- Offset<Vector<Offset<T>>> CreateVector(const Offset<T> *v, size_t len) {
- StartVector(len, sizeof(Offset<T>));
- for (auto i = len; i > 0;) { PushElement(v[--i]); }
- return Offset<Vector<Offset<T>>>(EndVector(len));
- }
-
- /// @brief Serialize a `std::vector` into a FlatBuffer `vector`.
- /// @tparam T The data type of the `std::vector` elements.
- /// @param v A const reference to the `std::vector` to serialize into the
- /// buffer as a `vector`.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- template<typename T> Offset<Vector<T>> CreateVector(const std::vector<T> &v) {
- return CreateVector(data(v), v.size());
- }
-
- // vector<bool> may be implemented using a bit-set, so we can't access it as
- // an array. Instead, read elements manually.
- // Background: https://isocpp.org/blog/2012/11/on-vectorbool
- Offset<Vector<uint8_t>> CreateVector(const std::vector<bool> &v) {
- StartVector(v.size(), sizeof(uint8_t));
- for (auto i = v.size(); i > 0;) {
- PushElement(static_cast<uint8_t>(v[--i]));
- }
- return Offset<Vector<uint8_t>>(EndVector(v.size()));
- }
-
- // clang-format off
- #ifndef FLATBUFFERS_CPP98_STL
- /// @brief Serialize values returned by a function into a FlatBuffer `vector`.
- /// This is a convenience function that takes care of iteration for you.
- /// @tparam T The data type of the `std::vector` elements.
- /// @param f A function that takes the current iteration 0..vector_size-1 and
- /// returns any type that you can construct a FlatBuffers vector out of.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- template<typename T> Offset<Vector<T>> CreateVector(size_t vector_size,
- const std::function<T (size_t i)> &f) {
- std::vector<T> elems(vector_size);
- for (size_t i = 0; i < vector_size; i++) elems[i] = f(i);
- return CreateVector(elems);
- }
- #endif
- // clang-format on
-
- /// @brief Serialize values returned by a function into a FlatBuffer `vector`.
- /// This is a convenience function that takes care of iteration for you.
- /// @tparam T The data type of the `std::vector` elements.
- /// @param f A function that takes the current iteration 0..vector_size-1,
- /// and the state parameter returning any type that you can construct a
- /// FlatBuffers vector out of.
- /// @param state State passed to f.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- template<typename T, typename F, typename S>
- Offset<Vector<T>> CreateVector(size_t vector_size, F f, S *state) {
- std::vector<T> elems(vector_size);
- for (size_t i = 0; i < vector_size; i++) elems[i] = f(i, state);
- return CreateVector(elems);
- }
-
- /// @brief Serialize a `std::vector<std::string>` into a FlatBuffer `vector`.
- /// This is a convenience function for a common case.
- /// @param v A const reference to the `std::vector` to serialize into the
- /// buffer as a `vector`.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- Offset<Vector<Offset<String>>> CreateVectorOfStrings(
- const std::vector<std::string> &v) {
- std::vector<Offset<String>> offsets(v.size());
- for (size_t i = 0; i < v.size(); i++) offsets[i] = CreateString(v[i]);
- return CreateVector(offsets);
- }
-
- /// @brief Serialize an array of structs into a FlatBuffer `vector`.
- /// @tparam T The data type of the struct array elements.
- /// @param[in] v A pointer to the array of type `T` to serialize into the
- /// buffer as a `vector`.
- /// @param[in] len The number of elements to serialize.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- template<typename T>
- Offset<Vector<const T *>> CreateVectorOfStructs(const T *v, size_t len) {
- StartVector(len * sizeof(T) / AlignOf<T>(), AlignOf<T>());
- PushBytes(reinterpret_cast<const uint8_t *>(v), sizeof(T) * len);
- return Offset<Vector<const T *>>(EndVector(len));
- }
-
- /// @brief Serialize an array of native structs into a FlatBuffer `vector`.
- /// @tparam T The data type of the struct array elements.
- /// @tparam S The data type of the native struct array elements.
- /// @param[in] v A pointer to the array of type `S` to serialize into the
- /// buffer as a `vector`.
- /// @param[in] len The number of elements to serialize.
- /// @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 &);
- std::vector<T> vv(len);
- std::transform(v, v + len, vv.begin(), Pack);
- return CreateVectorOfStructs<T>(data(vv), vv.size());
- }
-
- // clang-format off
- #ifndef FLATBUFFERS_CPP98_STL
- /// @brief Serialize an array of structs into a FlatBuffer `vector`.
- /// @tparam T The data type of the struct array elements.
- /// @param[in] filler A function that takes the current iteration 0..vector_size-1
- /// and a pointer to the struct that must be filled.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- /// This is mostly useful when flatbuffers are generated with mutation
- /// accessors.
- template<typename T> Offset<Vector<const T *>> CreateVectorOfStructs(
- size_t vector_size, const std::function<void(size_t i, T *)> &filler) {
- T* structs = StartVectorOfStructs<T>(vector_size);
- for (size_t i = 0; i < vector_size; i++) {
- filler(i, structs);
- structs++;
- }
- return EndVectorOfStructs<T>(vector_size);
- }
- #endif
- // clang-format on
-
- /// @brief Serialize an array of structs into a FlatBuffer `vector`.
- /// @tparam T The data type of the struct array elements.
- /// @param[in] f A function that takes the current iteration 0..vector_size-1,
- /// a pointer to the struct that must be filled and the state argument.
- /// @param[in] state Arbitrary state to pass to f.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- /// This is mostly useful when flatbuffers are generated with mutation
- /// accessors.
- template<typename T, typename F, typename S>
- Offset<Vector<const T *>> CreateVectorOfStructs(size_t vector_size, F f,
- S *state) {
- T *structs = StartVectorOfStructs<T>(vector_size);
- for (size_t i = 0; i < vector_size; i++) {
- f(i, structs, state);
- structs++;
- }
- return EndVectorOfStructs<T>(vector_size);
- }
-
- /// @brief Serialize a `std::vector` of structs into a FlatBuffer `vector`.
- /// @tparam T The data type of the `std::vector` struct elements.
- /// @param[in] v A const reference to the `std::vector` of structs to
- /// serialize into the buffer as a `vector`.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- template<typename T, typename Alloc>
- Offset<Vector<const T *>> CreateVectorOfStructs(
- const std::vector<T, Alloc> &v) {
- return CreateVectorOfStructs(data(v), v.size());
- }
-
- /// @brief Serialize a `std::vector` of native structs into a FlatBuffer
- /// `vector`.
- /// @tparam T The data type of the `std::vector` struct elements.
- /// @tparam S The data type of the `std::vector` native struct elements.
- /// @param[in] v A const reference to the `std::vector` of structs to
- /// serialize into the buffer as a `vector`.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- template<typename T, typename S>
- Offset<Vector<const T *>> CreateVectorOfNativeStructs(
- const std::vector<S> &v) {
- return CreateVectorOfNativeStructs<T, S>(data(v), v.size());
- }
-
- /// @cond FLATBUFFERS_INTERNAL
- template<typename T> struct StructKeyComparator {
- bool operator()(const T &a, const T &b) const {
- return a.KeyCompareLessThan(&b);
- }
-
- FLATBUFFERS_DELETE_FUNC(
- StructKeyComparator &operator=(const StructKeyComparator &))
- };
- /// @endcond
-
- /// @brief Serialize a `std::vector` of structs into a FlatBuffer `vector`
- /// in sorted order.
- /// @tparam T The data type of the `std::vector` struct elements.
- /// @param[in] v A const reference to the `std::vector` of structs to
- /// serialize into the buffer as a `vector`.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- template<typename T>
- Offset<Vector<const T *>> CreateVectorOfSortedStructs(std::vector<T> *v) {
- return CreateVectorOfSortedStructs(data(*v), v->size());
- }
-
- /// @brief Serialize a `std::vector` of native structs into a FlatBuffer
- /// `vector` in sorted order.
- /// @tparam T The data type of the `std::vector` struct elements.
- /// @tparam S The data type of the `std::vector` native struct elements.
- /// @param[in] v A const reference to the `std::vector` of structs to
- /// serialize into the buffer as a `vector`.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- template<typename T, typename S>
- Offset<Vector<const T *>> CreateVectorOfSortedNativeStructs(
- std::vector<S> *v) {
- return CreateVectorOfSortedNativeStructs<T, S>(data(*v), v->size());
- }
-
- /// @brief Serialize an array of structs into a FlatBuffer `vector` in sorted
- /// order.
- /// @tparam T The data type of the struct array elements.
- /// @param[in] v A pointer to the array of type `T` to serialize into the
- /// buffer as a `vector`.
- /// @param[in] len The number of elements to serialize.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- template<typename T>
- Offset<Vector<const T *>> CreateVectorOfSortedStructs(T *v, size_t len) {
- std::sort(v, v + len, StructKeyComparator<T>());
- return CreateVectorOfStructs(v, len);
- }
-
- /// @brief Serialize an array of native structs into a FlatBuffer `vector` in
- /// sorted order.
- /// @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 *>> CreateVectorOfSortedNativeStructs(S *v,
- size_t len) {
- extern T Pack(const S &);
- typedef T (*Pack_t)(const S &);
- std::vector<T> vv(len);
- std::transform(v, v + len, vv.begin(), static_cast<Pack_t &>(Pack));
- return CreateVectorOfSortedStructs<T>(vv, len);
- }
-
- /// @cond FLATBUFFERS_INTERNAL
- template<typename T> struct TableKeyComparator {
- TableKeyComparator(vector_downward &buf) : buf_(buf) {}
- TableKeyComparator(const TableKeyComparator &other) : buf_(other.buf_) {}
- bool operator()(const Offset<T> &a, const Offset<T> &b) const {
- auto table_a = reinterpret_cast<T *>(buf_.data_at(a.o));
- auto table_b = reinterpret_cast<T *>(buf_.data_at(b.o));
- return table_a->KeyCompareLessThan(table_b);
- }
- vector_downward &buf_;
-
- private:
- FLATBUFFERS_DELETE_FUNC(TableKeyComparator &operator=(const TableKeyComparator &other))
- };
- /// @endcond
-
- /// @brief Serialize an array of `table` offsets as a `vector` in the buffer
- /// in sorted order.
- /// @tparam T The data type that the offset refers to.
- /// @param[in] v An array of type `Offset<T>` that contains the `table`
- /// offsets to store in the buffer in sorted order.
- /// @param[in] len The number of elements to store in the `vector`.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- template<typename T>
- Offset<Vector<Offset<T>>> CreateVectorOfSortedTables(Offset<T> *v,
- size_t len) {
- std::sort(v, v + len, TableKeyComparator<T>(buf_));
- return CreateVector(v, len);
- }
-
- /// @brief Serialize an array of `table` offsets as a `vector` in the buffer
- /// in sorted order.
- /// @tparam T The data type that the offset refers to.
- /// @param[in] v An array of type `Offset<T>` that contains the `table`
- /// offsets to store in the buffer in sorted order.
- /// @return Returns a typed `Offset` into the serialized data indicating
- /// where the vector is stored.
- template<typename T>
- Offset<Vector<Offset<T>>> CreateVectorOfSortedTables(
- std::vector<Offset<T>> *v) {
- return CreateVectorOfSortedTables(data(*v), v->size());
- }
-
- /// @brief Specialized version of `CreateVector` for non-copying use cases.
- /// Write the data any time later to the returned buffer pointer `buf`.
- /// @param[in] len The number of elements to store in the `vector`.
- /// @param[in] elemsize The size of each element in the `vector`.
- /// @param[out] buf A pointer to a `uint8_t` pointer that can be
- /// written to at a later time to serialize the data into a `vector`
- /// in the buffer.
- uoffset_t CreateUninitializedVector(size_t len, size_t elemsize,
- uint8_t **buf) {
- NotNested();
- StartVector(len, elemsize);
- buf_.make_space(len * elemsize);
- auto vec_start = GetSize();
- auto vec_end = EndVector(len);
- *buf = buf_.data_at(vec_start);
- return vec_end;
- }
-
- /// @brief Specialized version of `CreateVector` for non-copying use cases.
- /// Write the data any time later to the returned buffer pointer `buf`.
- /// @tparam T The data type of the data that will be stored in the buffer
- /// as a `vector`.
- /// @param[in] len The number of elements to store in the `vector`.
- /// @param[out] buf A pointer to a pointer of type `T` that can be
- /// written to at a later time to serialize the data into a `vector`
- /// in the buffer.
- template<typename T>
- Offset<Vector<T>> CreateUninitializedVector(size_t len, T **buf) {
- AssertScalarT<T>();
- return CreateUninitializedVector(len, sizeof(T),
- reinterpret_cast<uint8_t **>(buf));
- }
-
- template<typename T>
- Offset<Vector<const T *>> CreateUninitializedVectorOfStructs(size_t len,
- T **buf) {
- return CreateUninitializedVector(len, sizeof(T),
- reinterpret_cast<uint8_t **>(buf));
- }
-
- // @brief Create a vector of scalar type T given as input a vector of scalar
- // type U, useful with e.g. pre "enum class" enums, or any existing scalar
- // data of the wrong type.
- template<typename T, typename U>
- Offset<Vector<T>> CreateVectorScalarCast(const U *v, size_t len) {
- AssertScalarT<T>();
- AssertScalarT<U>();
- StartVector(len, sizeof(T));
- for (auto i = len; i > 0;) { PushElement(static_cast<T>(v[--i])); }
- return Offset<Vector<T>>(EndVector(len));
- }
-
- /// @brief Write a struct by itself, typically to be part of a union.
- template<typename T> Offset<const T *> CreateStruct(const T &structobj) {
- NotNested();
- Align(AlignOf<T>());
- buf_.push_small(structobj);
- return Offset<const T *>(GetSize());
- }
-
- /// @brief The length of a FlatBuffer file header.
- static const size_t kFileIdentifierLength = 4;
-
- /// @brief Finish serializing a buffer by writing the root offset.
- /// @param[in] file_identifier If a `file_identifier` is given, the buffer
- /// will be prefixed with a standard FlatBuffers file header.
- template<typename T>
- void Finish(Offset<T> root, const char *file_identifier = nullptr) {
- Finish(root.o, file_identifier, false);
- }
-
- /// @brief Finish a buffer with a 32 bit size field pre-fixed (size of the
- /// buffer following the size field). These buffers are NOT compatible
- /// with standard buffers created by Finish, i.e. you can't call GetRoot
- /// on them, you have to use GetSizePrefixedRoot instead.
- /// All >32 bit quantities in this buffer will be aligned when the whole
- /// size pre-fixed buffer is aligned.
- /// These kinds of buffers are useful for creating a stream of FlatBuffers.
- template<typename T>
- void FinishSizePrefixed(Offset<T> root,
- const char *file_identifier = nullptr) {
- Finish(root.o, file_identifier, true);
- }
-
- void SwapBufAllocator(FlatBufferBuilder &other) {
- buf_.swap_allocator(other.buf_);
- }
-
- protected:
- // You shouldn't really be copying instances of this class.
- FlatBufferBuilder(const FlatBufferBuilder &);
- FlatBufferBuilder &operator=(const FlatBufferBuilder &);
-
- void Finish(uoffset_t root, const char *file_identifier, bool size_prefix) {
- NotNested();
- buf_.clear_scratch();
- // This will cause the whole buffer to be aligned.
- PreAlign((size_prefix ? sizeof(uoffset_t) : 0) + sizeof(uoffset_t) +
- (file_identifier ? kFileIdentifierLength : 0),
- minalign_);
- if (file_identifier) {
- FLATBUFFERS_ASSERT(strlen(file_identifier) == kFileIdentifierLength);
- PushBytes(reinterpret_cast<const uint8_t *>(file_identifier),
- kFileIdentifierLength);
- }
- PushElement(ReferTo(root)); // Location of root.
- if (size_prefix) { PushElement(GetSize()); }
- finished = true;
- }
-
- struct FieldLoc {
- uoffset_t off;
- voffset_t id;
- };
-
- vector_downward buf_;
-
- // Accumulating offsets of table members while it is being built.
- // We store these in the scratch pad of buf_, after the vtable offsets.
- uoffset_t num_field_loc;
- // Track how much of the vtable is in use, so we can output the most compact
- // possible vtable.
- voffset_t max_voffset_;
-
- // Ensure objects are not nested.
- bool nested;
-
- // Ensure the buffer is finished before it is being accessed.
- bool finished;
-
- size_t minalign_;
-
- bool force_defaults_; // Serialize values equal to their defaults anyway.
-
- bool dedup_vtables_;
-
- struct StringOffsetCompare {
- StringOffsetCompare(const vector_downward &buf) : buf_(&buf) {}
- bool operator()(const Offset<String> &a, const Offset<String> &b) const {
- auto stra = reinterpret_cast<const String *>(buf_->data_at(a.o));
- auto strb = reinterpret_cast<const String *>(buf_->data_at(b.o));
- return StringLessThan(stra->data(), stra->size(), strb->data(),
- strb->size());
- }
- const vector_downward *buf_;
- };
-
- // For use with CreateSharedString. Instantiated on first use only.
- typedef std::set<Offset<String>, StringOffsetCompare> StringOffsetMap;
- StringOffsetMap *string_pool;
-
- private:
- // Allocates space for a vector of structures.
- // Must be completed with EndVectorOfStructs().
- template<typename T> T *StartVectorOfStructs(size_t vector_size) {
- StartVector(vector_size * sizeof(T) / AlignOf<T>(), AlignOf<T>());
- return reinterpret_cast<T *>(buf_.make_space(vector_size * sizeof(T)));
- }
-
- // End the vector of structues in the flatbuffers.
- // Vector should have previously be started with StartVectorOfStructs().
- template<typename T>
- Offset<Vector<const T *>> EndVectorOfStructs(size_t vector_size) {
- return Offset<Vector<const T *>>(EndVector(vector_size));
- }
-};
-/// @}
-
-/// @cond FLATBUFFERS_INTERNAL
-// Helpers to get a typed pointer to the root object contained in the buffer.
-template<typename T> T *GetMutableRoot(void *buf) {
- EndianCheck();
- return reinterpret_cast<T *>(
- reinterpret_cast<uint8_t *>(buf) +
- EndianScalar(*reinterpret_cast<uoffset_t *>(buf)));
-}
-
-template<typename T> const T *GetRoot(const void *buf) {
- return GetMutableRoot<T>(const_cast<void *>(buf));
-}
-
-template<typename T> const T *GetSizePrefixedRoot(const void *buf) {
- return GetRoot<T>(reinterpret_cast<const uint8_t *>(buf) + sizeof(uoffset_t));
-}
-
-/// Helpers to get a typed pointer to objects that are currently being built.
-/// @warning Creating new objects will lead to reallocations and invalidates
-/// the pointer!
-template<typename T>
-T *GetMutableTemporaryPointer(FlatBufferBuilder &fbb, Offset<T> offset) {
- return reinterpret_cast<T *>(fbb.GetCurrentBufferPointer() + fbb.GetSize() -
- offset.o);
-}
-
-template<typename T>
-const T *GetTemporaryPointer(FlatBufferBuilder &fbb, Offset<T> offset) {
- return GetMutableTemporaryPointer<T>(fbb, offset);
-}
-
-/// @brief Get a pointer to the the file_identifier section of the buffer.
-/// @return Returns a const char pointer to the start of the file_identifier
-/// characters in the buffer. The returned char * has length
-/// 'flatbuffers::FlatBufferBuilder::kFileIdentifierLength'.
-/// This function is UNDEFINED for FlatBuffers whose schema does not include
-/// a file_identifier (likely points at padding or the start of a the root
-/// vtable).
-inline const char *GetBufferIdentifier(const void *buf,
- bool size_prefixed = false) {
- return reinterpret_cast<const char *>(buf) +
- ((size_prefixed) ? 2 * sizeof(uoffset_t) : sizeof(uoffset_t));
-}
-
-// Helper to see if the identifier in a buffer has the expected value.
-inline bool BufferHasIdentifier(const void *buf, const char *identifier,
- bool size_prefixed = false) {
- return strncmp(GetBufferIdentifier(buf, size_prefixed), identifier,
- FlatBufferBuilder::kFileIdentifierLength) == 0;
-}
-
-// Helper class to verify the integrity of a FlatBuffer
-class Verifier FLATBUFFERS_FINAL_CLASS {
- public:
- Verifier(const uint8_t *buf, size_t buf_len, uoffset_t _max_depth = 64,
- uoffset_t _max_tables = 1000000, bool _check_alignment = true)
- : buf_(buf),
- size_(buf_len),
- depth_(0),
- max_depth_(_max_depth),
- num_tables_(0),
- max_tables_(_max_tables),
- upper_bound_(0),
- check_alignment_(_check_alignment) {
- FLATBUFFERS_ASSERT(size_ < FLATBUFFERS_MAX_BUFFER_SIZE);
- }
-
- // Central location where any verification failures register.
- bool Check(bool ok) const {
- // clang-format off
- #ifdef FLATBUFFERS_DEBUG_VERIFICATION_FAILURE
- FLATBUFFERS_ASSERT(ok);
- #endif
- #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
- if (!ok)
- upper_bound_ = 0;
- #endif
- // clang-format on
- return ok;
- }
-
- // Verify any range within the buffer.
- bool Verify(size_t elem, size_t elem_len) const {
- // clang-format off
- #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
- auto upper_bound = elem + elem_len;
- if (upper_bound_ < upper_bound)
- upper_bound_ = upper_bound;
- #endif
- // clang-format on
- return Check(elem_len < size_ && elem <= size_ - elem_len);
- }
-
- template<typename T> bool VerifyAlignment(size_t elem) const {
- return Check((elem & (sizeof(T) - 1)) == 0 || !check_alignment_);
- }
-
- // Verify a range indicated by sizeof(T).
- template<typename T> bool Verify(size_t elem) const {
- return VerifyAlignment<T>(elem) && Verify(elem, sizeof(T));
- }
-
- bool VerifyFromPointer(const uint8_t *p, size_t len) {
- auto o = static_cast<size_t>(p - buf_);
- return Verify(o, len);
- }
-
- // Verify relative to a known-good base pointer.
- bool Verify(const uint8_t *base, voffset_t elem_off, size_t elem_len) const {
- return Verify(static_cast<size_t>(base - buf_) + elem_off, elem_len);
- }
-
- template<typename T>
- bool Verify(const uint8_t *base, voffset_t elem_off) const {
- return Verify(static_cast<size_t>(base - buf_) + elem_off, sizeof(T));
- }
-
- // Verify a pointer (may be NULL) of a table type.
- template<typename T> bool VerifyTable(const T *table) {
- return !table || table->Verify(*this);
- }
-
- // Verify a pointer (may be NULL) of any vector type.
- template<typename T> bool VerifyVector(const Vector<T> *vec) const {
- return !vec || VerifyVectorOrString(reinterpret_cast<const uint8_t *>(vec),
- sizeof(T));
- }
-
- // Verify a pointer (may be NULL) of a vector to struct.
- template<typename T> bool VerifyVector(const Vector<const T *> *vec) const {
- return VerifyVector(reinterpret_cast<const Vector<T> *>(vec));
- }
-
- // Verify a pointer (may be NULL) to string.
- bool VerifyString(const String *str) const {
- size_t end;
- return !str || (VerifyVectorOrString(reinterpret_cast<const uint8_t *>(str),
- 1, &end) &&
- Verify(end, 1) && // Must have terminator
- Check(buf_[end] == '\0')); // Terminating byte must be 0.
- }
-
- // Common code between vectors and strings.
- bool VerifyVectorOrString(const uint8_t *vec, size_t elem_size,
- size_t *end = nullptr) const {
- auto veco = static_cast<size_t>(vec - buf_);
- // Check we can read the size field.
- if (!Verify<uoffset_t>(veco)) return false;
- // Check the whole array. If this is a string, the byte past the array
- // must be 0.
- auto size = ReadScalar<uoffset_t>(vec);
- auto max_elems = FLATBUFFERS_MAX_BUFFER_SIZE / elem_size;
- if (!Check(size < max_elems))
- return false; // Protect against byte_size overflowing.
- auto byte_size = sizeof(size) + elem_size * size;
- if (end) *end = veco + byte_size;
- return Verify(veco, byte_size);
- }
-
- // Special case for string contents, after the above has been called.
- bool VerifyVectorOfStrings(const Vector<Offset<String>> *vec) const {
- if (vec) {
- for (uoffset_t i = 0; i < vec->size(); i++) {
- if (!VerifyString(vec->Get(i))) return false;
- }
- }
- return true;
- }
-
- // Special case for table contents, after the above has been called.
- template<typename T> bool VerifyVectorOfTables(const Vector<Offset<T>> *vec) {
- if (vec) {
- for (uoffset_t i = 0; i < vec->size(); i++) {
- if (!vec->Get(i)->Verify(*this)) return false;
- }
- }
- return true;
- }
-
- __supress_ubsan__("unsigned-integer-overflow") bool VerifyTableStart(
- const uint8_t *table) {
- // Check the vtable offset.
- auto tableo = static_cast<size_t>(table - buf_);
- if (!Verify<soffset_t>(tableo)) return false;
- // This offset may be signed, but doing the subtraction unsigned always
- // gives the result we want.
- auto vtableo = tableo - static_cast<size_t>(ReadScalar<soffset_t>(table));
- // Check the vtable size field, then check vtable fits in its entirety.
- return VerifyComplexity() && Verify<voffset_t>(vtableo) &&
- VerifyAlignment<voffset_t>(ReadScalar<voffset_t>(buf_ + vtableo)) &&
- Verify(vtableo, ReadScalar<voffset_t>(buf_ + vtableo));
- }
-
- template<typename T>
- bool VerifyBufferFromStart(const char *identifier, size_t start) {
- if (identifier && !Check((size_ >= 2 * sizeof(flatbuffers::uoffset_t) &&
- BufferHasIdentifier(buf_ + start, identifier)))) {
- return false;
- }
-
- // Call T::Verify, which must be in the generated code for this type.
- auto o = VerifyOffset(start);
- return o && reinterpret_cast<const T *>(buf_ + start + o)->Verify(*this)
- // clang-format off
- #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
- && GetComputedSize()
- #endif
- ;
- // clang-format on
- }
-
- // Verify this whole buffer, starting with root type T.
- template<typename T> bool VerifyBuffer() { return VerifyBuffer<T>(nullptr); }
-
- template<typename T> bool VerifyBuffer(const char *identifier) {
- return VerifyBufferFromStart<T>(identifier, 0);
- }
-
- template<typename T> bool VerifySizePrefixedBuffer(const char *identifier) {
- return Verify<uoffset_t>(0U) &&
- ReadScalar<uoffset_t>(buf_) == size_ - sizeof(uoffset_t) &&
- VerifyBufferFromStart<T>(identifier, sizeof(uoffset_t));
- }
-
- uoffset_t VerifyOffset(size_t start) const {
- if (!Verify<uoffset_t>(start)) return 0;
- auto o = ReadScalar<uoffset_t>(buf_ + start);
- // May not point to itself.
- if (!Check(o != 0)) return 0;
- // Can't wrap around / buffers are max 2GB.
- if (!Check(static_cast<soffset_t>(o) >= 0)) return 0;
- // Must be inside the buffer to create a pointer from it (pointer outside
- // buffer is UB).
- if (!Verify(start + o, 1)) return 0;
- return o;
- }
-
- uoffset_t VerifyOffset(const uint8_t *base, voffset_t start) const {
- return VerifyOffset(static_cast<size_t>(base - buf_) + start);
- }
-
- // Called at the start of a table to increase counters measuring data
- // structure depth and amount, and possibly bails out with false if
- // limits set by the constructor have been hit. Needs to be balanced
- // with EndTable().
- bool VerifyComplexity() {
- depth_++;
- num_tables_++;
- return Check(depth_ <= max_depth_ && num_tables_ <= max_tables_);
- }
-
- // Called at the end of a table to pop the depth count.
- bool EndTable() {
- depth_--;
- return true;
- }
-
- // Returns the message size in bytes
- size_t GetComputedSize() const {
- // clang-format off
- #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
- uintptr_t size = upper_bound_;
- // Align the size to uoffset_t
- size = (size - 1 + sizeof(uoffset_t)) & ~(sizeof(uoffset_t) - 1);
- return (size > size_) ? 0 : size;
- #else
- // Must turn on FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE for this to work.
- (void)upper_bound_;
- FLATBUFFERS_ASSERT(false);
- return 0;
- #endif
- // clang-format on
- }
-
- private:
- const uint8_t *buf_;
- size_t size_;
- uoffset_t depth_;
- uoffset_t max_depth_;
- uoffset_t num_tables_;
- uoffset_t max_tables_;
- mutable size_t upper_bound_;
- bool check_alignment_;
-};
-
-// Convenient way to bundle a buffer and its length, to pass it around
-// typed by its root.
-// A BufferRef does not own its buffer.
-struct BufferRefBase {}; // for std::is_base_of
-template<typename T> struct BufferRef : BufferRefBase {
- BufferRef() : buf(nullptr), len(0), must_free(false) {}
- BufferRef(uint8_t *_buf, uoffset_t _len)
- : buf(_buf), len(_len), must_free(false) {}
-
- ~BufferRef() {
- if (must_free) free(buf);
- }
-
- const T *GetRoot() const { return flatbuffers::GetRoot<T>(buf); }
-
- bool Verify() {
- Verifier verifier(buf, len);
- return verifier.VerifyBuffer<T>(nullptr);
- }
-
- uint8_t *buf;
- uoffset_t len;
- bool must_free;
-};
-
-// "structs" are flat structures that do not have an offset table, thus
-// always have all members present and do not support forwards/backwards
-// compatible extensions.
-
-class Struct FLATBUFFERS_FINAL_CLASS {
- public:
- template<typename T> T GetField(uoffset_t o) const {
- return ReadScalar<T>(&data_[o]);
- }
-
- template<typename T> T GetStruct(uoffset_t o) const {
- return reinterpret_cast<T>(&data_[o]);
- }
-
- const uint8_t *GetAddressOf(uoffset_t o) const { return &data_[o]; }
- uint8_t *GetAddressOf(uoffset_t o) { return &data_[o]; }
-
- private:
- // private constructor & copy constructor: you obtain instances of this
- // class by pointing to existing data only
- Struct();
- Struct(const Struct &);
- Struct &operator=(const Struct &);
-
- uint8_t data_[1];
-};
-
-// "tables" use an offset table (possibly shared) that allows fields to be
-// omitted and added at will, but uses an extra indirection to read.
-class Table {
- public:
- const uint8_t *GetVTable() const {
- return data_ - ReadScalar<soffset_t>(data_);
- }
-
- // This gets the field offset for any of the functions below it, or 0
- // if the field was not present.
- voffset_t GetOptionalFieldOffset(voffset_t field) const {
- // The vtable offset is always at the start.
- auto vtable = GetVTable();
- // The first element is the size of the vtable (fields + type id + itself).
- auto vtsize = ReadScalar<voffset_t>(vtable);
- // If the field we're accessing is outside the vtable, we're reading older
- // data, so it's the same as if the offset was 0 (not present).
- return field < vtsize ? ReadScalar<voffset_t>(vtable + field) : 0;
- }
-
- template<typename T> T GetField(voffset_t field, T defaultval) const {
- auto field_offset = GetOptionalFieldOffset(field);
- return field_offset ? ReadScalar<T>(data_ + field_offset) : defaultval;
- }
-
- template<typename P> P GetPointer(voffset_t field) {
- auto field_offset = GetOptionalFieldOffset(field);
- auto p = data_ + field_offset;
- return field_offset ? reinterpret_cast<P>(p + ReadScalar<uoffset_t>(p))
- : nullptr;
- }
- template<typename P> P GetPointer(voffset_t field) const {
- return const_cast<Table *>(this)->GetPointer<P>(field);
- }
-
- template<typename P> P GetStruct(voffset_t field) const {
- auto field_offset = GetOptionalFieldOffset(field);
- auto p = const_cast<uint8_t *>(data_ + field_offset);
- return field_offset ? reinterpret_cast<P>(p) : nullptr;
- }
-
- template<typename Raw, typename Face>
- flatbuffers::Optional<Face> GetOptional(voffset_t field) const {
- auto field_offset = GetOptionalFieldOffset(field);
- auto p = data_ + field_offset;
- return field_offset ? Optional<Face>(static_cast<Face>(ReadScalar<Raw>(p)))
- : Optional<Face>();
- }
-
- template<typename T> bool SetField(voffset_t field, T val, T def) {
- auto field_offset = GetOptionalFieldOffset(field);
- if (!field_offset) return IsTheSameAs(val, def);
- WriteScalar(data_ + field_offset, val);
- return true;
- }
- template<typename T> bool SetField(voffset_t field, T val) {
- auto field_offset = GetOptionalFieldOffset(field);
- if (!field_offset) return false;
- WriteScalar(data_ + field_offset, val);
- return true;
- }
-
- bool SetPointer(voffset_t field, const uint8_t *val) {
- auto field_offset = GetOptionalFieldOffset(field);
- if (!field_offset) return false;
- WriteScalar(data_ + field_offset,
- static_cast<uoffset_t>(val - (data_ + field_offset)));
- return true;
- }
-
- uint8_t *GetAddressOf(voffset_t field) {
- auto field_offset = GetOptionalFieldOffset(field);
- return field_offset ? data_ + field_offset : nullptr;
- }
- const uint8_t *GetAddressOf(voffset_t field) const {
- return const_cast<Table *>(this)->GetAddressOf(field);
- }
-
- bool CheckField(voffset_t field) const {
- return GetOptionalFieldOffset(field) != 0;
- }
-
- // Verify the vtable of this table.
- // Call this once per table, followed by VerifyField once per field.
- bool VerifyTableStart(Verifier &verifier) const {
- return verifier.VerifyTableStart(data_);
- }
-
- // Verify a particular field.
- template<typename T>
- bool VerifyField(const Verifier &verifier, voffset_t field) const {
- // Calling GetOptionalFieldOffset should be safe now thanks to
- // VerifyTable().
- auto field_offset = GetOptionalFieldOffset(field);
- // Check the actual field.
- return !field_offset || verifier.Verify<T>(data_, field_offset);
- }
-
- // VerifyField for required fields.
- template<typename T>
- bool VerifyFieldRequired(const Verifier &verifier, voffset_t field) const {
- auto field_offset = GetOptionalFieldOffset(field);
- return verifier.Check(field_offset != 0) &&
- verifier.Verify<T>(data_, field_offset);
- }
-
- // Versions for offsets.
- bool VerifyOffset(const Verifier &verifier, voffset_t field) const {
- auto field_offset = GetOptionalFieldOffset(field);
- return !field_offset || verifier.VerifyOffset(data_, field_offset);
- }
-
- bool VerifyOffsetRequired(const Verifier &verifier, voffset_t field) const {
- auto field_offset = GetOptionalFieldOffset(field);
- return verifier.Check(field_offset != 0) &&
- verifier.VerifyOffset(data_, field_offset);
- }
-
- private:
- // private constructor & copy constructor: you obtain instances of this
- // class by pointing to existing data only
- Table();
- Table(const Table &other);
- Table &operator=(const Table &);
-
- uint8_t data_[1];
-};
-
-// This specialization allows avoiding warnings like:
-// MSVC C4800: type: forcing value to bool 'true' or 'false'.
-template<>
-inline flatbuffers::Optional<bool> Table::GetOptional<uint8_t, bool>(
- voffset_t field) const {
- auto field_offset = GetOptionalFieldOffset(field);
- auto p = data_ + field_offset;
- return field_offset ? Optional<bool>(ReadScalar<uint8_t>(p) != 0)
- : Optional<bool>();
-}
-
-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;
-}
/// @brief This can compute the start of a FlatBuffer from a root pointer, i.e.
/// it is the opposite transformation of GetRoot().
@@ -2661,7 +56,7 @@
// file_identifier, and alignment padding) to see which points to the root.
// None of the other values can "impersonate" the root since they will either
// be 0 or four ASCII characters.
- static_assert(FlatBufferBuilder::kFileIdentifierLength == sizeof(uoffset_t),
+ static_assert(flatbuffers::kFileIdentifierLength == sizeof(uoffset_t),
"file_identifier is assumed to be the same size as uoffset_t");
for (auto possible_roots = FLATBUFFERS_MAX_ALIGNMENT / sizeof(uoffset_t) + 1;
possible_roots; possible_roots--) {
@@ -2697,16 +92,9 @@
/// if you wish. The resolver does the opposite lookup, for when the object
/// is being serialized again.
typedef uint64_t hash_value_t;
-// clang-format off
-#ifdef FLATBUFFERS_CPP98_STL
- typedef void (*resolver_function_t)(void **pointer_adr, hash_value_t hash);
- typedef hash_value_t (*rehasher_function_t)(void *pointer);
-#else
- typedef std::function<void (void **pointer_adr, hash_value_t hash)>
- resolver_function_t;
- typedef std::function<hash_value_t (void *pointer)> rehasher_function_t;
-#endif
-// clang-format on
+typedef std::function<void(void **pointer_adr, hash_value_t hash)>
+ resolver_function_t;
+typedef std::function<hash_value_t(void *pointer)> rehasher_function_t;
// Helper function to test if a field is present, using any of the field
// enums in the generated code.
@@ -2763,7 +151,7 @@
// Minimal reflection via code generation.
// Besides full-fat reflection (see reflection.h) and parsing/printing by
-// loading schemas (see idl.h), we can also have code generation for mimimal
+// loading schemas (see idl.h), we can also have code generation for minimal
// reflection data which allows pretty-printing and other uses without needing
// a schema or a parser.
// Generate code with --reflect-types (types only) or --reflect-names (names
@@ -2812,9 +200,12 @@
// bitfields is otherwise implementation-defined and causes warnings on older
// GCC compilers.
struct TypeCode {
- unsigned short base_type : 4; // ElementaryType
- unsigned short is_repeating : 1; // Either vector (in table) or array (in struct)
- signed short sequence_ref : 11; // Index into type_refs below, or -1 for none.
+ // ElementaryType
+ unsigned short base_type : 4;
+ // Either vector (in table) or array (in struct)
+ unsigned short is_repeating : 1;
+ // Index into type_refs below, or -1 for none.
+ signed short sequence_ref : 11;
};
static_assert(sizeof(TypeCode) == 2, "TypeCode");
@@ -2835,27 +226,13 @@
};
// String which identifies the current version of FlatBuffers.
-// flatbuffer_version_string is used by Google developers to identify which
-// applications uploaded to Google Play are using this library. This allows
-// the development team at Google to determine the popularity of the library.
-// How it works: Applications that are uploaded to the Google Play Store are
-// scanned for this version string. We track which applications are using it
-// to measure popularity. You are free to remove it (of course) but we would
-// appreciate if you left it in.
+inline const char *flatbuffers_version_string() {
+ return "FlatBuffers " FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MAJOR) "."
+ FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MINOR) "."
+ FLATBUFFERS_STRING(FLATBUFFERS_VERSION_REVISION);
+}
-// Weak linkage is culled by VS & doesn't work on cygwin.
// clang-format off
-#if !defined(_WIN32) && !defined(__CYGWIN__)
-
-extern volatile __attribute__((weak)) const char *flatbuffer_version_string;
-volatile __attribute__((weak)) const char *flatbuffer_version_string =
- "FlatBuffers "
- FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MAJOR) "."
- FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MINOR) "."
- FLATBUFFERS_STRING(FLATBUFFERS_VERSION_REVISION);
-
-#endif // !defined(_WIN32) && !defined(__CYGWIN__)
-
#define FLATBUFFERS_DEFINE_BITMASK_OPERATORS(E, T)\
inline E operator | (E lhs, E rhs){\
return E(T(lhs) | T(rhs));\