Squashed 'third_party/flatbuffers/' changes from acc9990ab..d6a8dbd26
d6a8dbd26 Experimental fix for failing oss-fuzz coverage build (#6259)
ed391e177 BREAKING: Rust flexbuffers serde human readable set to false (#6257)
a49531414 Update to flags in fuzzing-cmake file (#6256)
de1f0342c Remove _POSIX_C_SOURCE and _XOPEN_SOURCE definitions when compiling o… (#6205)
d0d51e2a5 flatc should support --binary --schema with optional scalar fields. (#6252)
33ab26017 Bump version of rules_go to 0.24.5 (#6234)
febb9d87c Union As Accessors for C# (#6251)
8778dc7c2 Resets buffer without deallocating current pointer (#6247)
aae376e9a Add GetBufferSpan() function to bufferbuilder (#6235)
0ff047148 Modernize android build and sample (#6229)
46a8c7e95 Added required-nested-flatbuffer to monster_test and fixed rust (#6236)
bc56c553e Notify based on Labelling issues and PR (#6241)
07d7cd78a Converted globs to use single quotes (#6240)
cdef70e24 More adjustments to the auto labeler (#6239)
9dd44df35 Updated Lua labeller glob (#6238)
c9b29d088 Support size-prefixed buffers and add tests for size-prefixed messages (#6232)
fba93e0ab Removes duplicate swift in labeler (#6228)
d1a545b1f Added more labels for auto labeler (#6227)
ea92a668d [C#] Optional Scalars (#6217)
6034de286 [Label Bot] Add Java and Kotlin support for the label bot (#6226)
b08b0a440 Implement `Debug` trait for Rust flatbuffers. (#6207)
17ae48dec [Label Bot] Adds some languages to labeler bot (#6222)
fc8097925 Auto Labeler Setup, Just C# for now (#6221)
55658f523 Auto Labeler Setup, Just C# for now (#6218)
14ecfe423 Updated comments and fixed a fundamental type error. (#6214)
a0182cdb1 optional scalars for ts/js (#6215)
0dfcc0a37 Adds NetTest.bat to run .NET Core tests on Windows (#6216)
f9a18ea63 [Java] Implement optional scalars (#6212)
c7586e85a Empties the sharedString map on reset on go and csharp (#6187)
914c64601 Removed C# references from java generator. Move annotations closer to definitions (#6204)
42d7c7997 Adds readable size to asserts in read functions (#6210)
e68e8d7de Refactor idl_gen_rust (#6206)
84809be7e Fix typo in flatbuffers::span declaration. (#6202)
1606fb637 Kotlin test optional enum (#6201)
fe8e3c7e5 Mass Refactoring to use `IsString` and other BASE_TYPE helpers (#6193)
8f6fa4b71 Updated SupportsAdvancedUnionFeatures to look out for string (#6190)
b46db38f5 [JS/TS] Rewrite flexbuffers JS to TS (#6148)
9fa1d2705 Rework enums in rust. (#6098)
a402b3aba idl_gen_json_schema Fix generation of arrays of enums (#6184)
0e1415b99 fix(go_test): remove deprecated grpc call (#6183)
5cd713710 Add generation of JSON Schema to library (#6165)
5be777e1d Bump junit from 4.12 to 4.13.1 in /grpc/tests (#6173)
a49d440ec Bump junit from 4.12 to 4.13.1 in /grpc (#6172)
4ec5e8db9 [C++] Add option to not generate direct copy methods. (#6166)
04bec23a3 Add Array initialization from struct constructor (#5865) (#6147)
77d57fd07 Cast to right type for reserved_ subtraction (#6167)
543c1bbeb Fixed rust nested flatbuffers for tables other than self (#6062)
cb971eece [C++] Fix -Wnarrowing and -Woverflow due to signed bitfields on G++ ARM (#6163)
7b9e61fcc [TS] GRPC Implementation (#6141)
3359e3042 Moved C++ to optional_scalars2 and added some tests. (#6162)
187a4787f [Rust] Upgrade flatbuffers library to 2018 edition (#6159)
08943aa26 Flatbuffer C++ UnpackTo optimization for vectors of non-bool bytes. (#6154)
5975658eb Enables optional enums in swift (#6160)
5d3cf440e Updated Lobster test for optional bools/enums
8ec8322f0 Ruopt enum (#6156)
bbcc85fd4 Fix generation of C++ code with Optional<Enum> (#6155)
0bdf2fa15 [C#] Fix and improve project files (#6142)
2eedc769d possibility to create a vector from an iterator (#6135)
ab01ae162 flatc should output a warning, when an attribute is attached more than once (#6146)
689bfafa7 [Python/JS/TS] Codegen SizeOf method for structs (#6136)
641309a5b unix2dos on tests/FlatBuffers.Test/FlatBuffers.Core.Test.csproj (#6133)
52e362879 SpanT is available in .Net Standard 2.0. (#6137)
dca12522a Add static cast to avoid implicit double promotion. (#6132)
e0bbaa6f9 [C#]Change to ENABLE_SPAN_T that doesn't require UNSAFE_BYTEBUFFER. (#6073)
ab139d6be Revert "[C#] Fix and improve project files (#6116)" (#6130)
34d67b425 Minireflect fixed array (#6129)
96d5e3597 [JS/TS] fix flatbuffers default export (#6123)
eb686a86f Add missed file generated by optional_scalar.fbs (#6125)
750281630 [C#] Fix and improve project files (#6116)
fb4e1c34f Add CharToLower and CharToUpper into util.s (#6126)
8c67b5b12 Add support of Optional<T> scalars to C++ code generator (#6092)
6228b66d3 [Kotlin] Support for optional scalars. (#6115)
e1be8aaad Bump version for latest swift version (#6121)
94873e595 [JS/TS] Modernize TypeScript / JavaScript flatbuffers support (#6095)
b8e87fafe [JS] Add getFullyQualifiedName() (#6119)
f96d1ef74 [Java] allowing larger buffer sizes when growing a byte buffer (#6118)
89435303b [Swift] Migrates struct write APIS to write directly to the buffer (#6093)
c75ae2429 Optional-ness in reflection (#6097)
338944d3d Rename Nullable scalars to Optional scalars (#6112)
f5ab24bc4 Avoid memcpy call for empty vectors (#6111)
92a8c1a0f [JS] FlexBuffers Fix for wrong type of offset and length values (#6107)
6cea45dcd fix c# json serializer commandline argument docs (#6104)
fec58aa12 Fix for issue 6100: incorrect shrinking logic in ResizeContext() (#6102)
71aca81ff [JS] FlexBuffers Support (#5973)
04d87ffec [C++] Small refactoring of the C++ code generator (#6091)
bb25956f0 Wrap verify file id condition in Check call (#6085)
49f4948f0 + Add `removable-media` plug to the snapcraft config (#6083)
eeacc53d2 Adds proper access types for swift object api & flatbuffers & grpc (#6081)
f3003e08d [Lobster] missed a test
d713a0084 [CMake] enabled multi-core builds in VS projects
77f966f89 [Lobster] optional scalars support
e86d5b8e9 [Kotlin] Attach JvmStatic annotation to each method in companion object (#6052)
db2aa9b4e [C#] Cleaned up .NET testing script for Mono (#6016)
63cc0eec4 Adds a serialize helper function to native table (#6059)
c30a87de6 [TS] Fix four bugs with imported types in TypeScript. (#6054)
a0fb30575 [Swift] Append namespace for Swift Grpc implementation (#6049)
77c18c1d6 export a __version__ variable for python module (#5309)
f1f23d08e adding fb import when no other imports are present (#6030)
f1025b284 [Feature] Checks for Nullable strings (#6050)
5d052f4e5 [Swift] RFC: Switch Swift namespace from public enum to ordinary concat with _ (#6045)
18b015d25 Rust codegen improvements and lint fixes (#6046)
d76e93f27 adds code gen for optional scalars in swift (#6038)
82fac326c [C++] Fix compiler error from deleted assignment operator (#6036) (#6047)
043b52bd4 Optional Scalars support for Rust (#6034)
c8fa0afdf Allow to run cpp tests under grpc/tests/ using bazel. (#6040)
6d0aae73c Fix git command executed in wrong folder when doing cmake superbuild (#6039)
ff1b73128 [Swift] Optional Scalars Preparation (#6028)
2e48c8dd3 tests: Check for both quiet and signaling NaN on mipsel/hppa (#6029)
6942704f2 support deprecated flag in json schema (#6022)
9ecd2e16c Flatc parser support for nullable scalars (#6026)
33e2d8079 [Dart] Generate constant values map for enums (#6025)
969d0f7a6 Using proper symbol name for reexport (#6021)
515a4052a Silence false positive "-Wstringop-overflow" on GCC 10.0 to 11.0 (#6020)
36fbe6f13 Updated FB import (#6019)
b69fc8cc9 [Java] Add support for shared strings on FlatBufferBuilder. (#6012)
ab6af18d9 Not using non-existent create method for obj api (#6015)
37a5dee10 Code cleanup + updates test and readme (#6004)
8a721f69a Serde with bytes maps to Blob (#6009)
e810635ea [Swift] FlatBuffers createMonster method doesn't treat struct properly (#5992)
4995e1527 Manage grpc dependency in Bazel's WORKSPACE file. (#5995)
60b6066fe Add warning to schema parser if field name is not snake_case. (#6005)
35d45cac7 [Rust] Flexbuffers dependency cleanup and fixes (#5998)
165a6e3d1 Re-added Evolution Schema Code Generation Command (#5999)
13d3fb2ea Fix RPM install conflict (#6003)
d64078eb2 [Swift] Initialize memory when clear ByteBuffer (#5982)
ca1190a3d [TS] Use proper TypedArray in create*Vector (#5991)
7571b2ac5 [C++] Updates real_path to be truly portable (#5787)
e5a8f76a4 [C++] Generate default member initializers for >= C++11 (#5989)
413bb9b55 [Kotlin] Fix Access to union of vector element (#5994)
f35184aef [Swift] Add parsing from unowned UnsafeMutableRawPointer for ByteBuffer (#5981)
b124b7625 Removed requirement that enums be declared in ascending order. (#5887)
0ec7600c6 Do not remove the last digit from float values (#5974)
14baf45c9 Mark GetBufferMinAlignment() const (#5985)
9abb2ec2c TypeScript/JavaScript docs improvements (#5984)
2e57d80b1 [Swift] Internal library improvements (#5965)
cfc7753a4 [Doc] Added missing letters to compiler options (#5976)
12ddc8a92 Rust Flexbuffers Documentation update (#5979)
24ad35709 [docs] typo: updates monsterdata.json to be valid json (#5978)
cc44a4442 [idl_parser] Mark typefield as deprecated (#5958)
9ab4a5c0e Deleted old stale bot
6682cfe87 Increased Operations per run in stale.yml
64922904b Adding Stale Action to clean up PR and Issues
8e505cb67 [C++] Fixed/Enabled --cpp-ptr-type std::shared_ptr [#5813] (#5959)
a28357d7a Propagate boolean default values from proto to fbs (#5964)
7cb4762a6 [Swift] Improving reallocation time by using memcpy and moving reallocation code to storage (#5960)
4e45f7c9e Fix error in SimpleQSort (#5955)
7ac026405 fix error on GRPC Python - ignore namespace tree if not specified (#5862) (#5922)
108e981db Required is now implemented in swift (#5952)
94a78e385 Fixed: Access violation and ASAN/UNSAN failures with sorted tables
53fb453e0 [rust] Add FlatBufferBuilder::force_defaults API (#5946)
17c1f35fa [FlexBuffer][Java] ReadWriteBuf and ReadBuf interface public (#5948)
2eaf57778 [Java] Grow ArrayReadWriteBuf enough to match requested capacity. (#5921)
666800da3 Adds bool support in structs + updates grpc support + CI upgrades (#5943)
38ed69eb3 fixed mutating inline values (#5942)
d026e6f07 Add static asserts to ensure that reflection API arrays are kept in sync (#5934)
988164f6e [C++] Got rid of memset's in constructors (#5938)
7179a5a8b General Codebase clean up (#5939)
a0da0c08c Add GetStringView like GetString, GetCstring (#5937)
ac203b209 [C#] Add file identifier to ObjectAPI Serialization Utility. (#5920)
8dd1bf25b not creating creation methods when using structs (#5919)
5aa443d98 [Dart] Adding FlexBuffers support (#5853)
0fa087657 [Dart] Getting tests/DartTest.sh to work on master. (#5915)
424a473e1 Schema parser: prohibit declaration of an array of pointers inside structs (#5907)
c3faa8346 Fix Cargo.toml dependencies (#5911)
91399ad05 fix union type names (#5902)
32782e4ad Update Rust Flexbuffers metadata before publishing (#5905)
e7f3b1690 [TS] Make Obj-API work with --short-names (#5898)
12ed1fe4a fixed invalid imports with --gen-all (#5895)
85ee4df7a [C#] Thread safe reads of Double and Float values from a ByteBuffer (#5900)
de89bd193 Implement flexbuffers in python (#5880)
8be05f6bd Rust Flexbuffers (#5669)
870ecbc09 [swift] Moves code to use VTablesStorage (#5888)
c2da8d5d8 [Java][FlexBuffers] Make FlexBuffersBuilder reusable by adding clear() (#5889) (#5890)
e84cbff67 Align package name to FindFlatBuffers.cmake (#5899)
f94e6c84e Small tutorial improvements - documentation only (#5894)
f12cca8bc Attempt at adding Github Actions CI
7e4124d6e Handle git program or .git folder absence (#5878)
a875d247a only add native_include_files if object based api is enabled (#5886)
6e9f5d981 Respect shared attribute in Parser (#5885)
ff1c78233 include/flatbuffers: typo fixes in comments (#5884)
2e9a19673 Updates swift docs for package management (#5883)
e3cb07d32 [Rust] idl_gen_rust.cpp: (Option/required-aware codegen for unions) (#5850)
712866d57 Propagate use_string_pooling in CopyTable (#5879)
44c919a9e Not using reexports with --gen-all (#5873)
99aa1ef21 Added INCLUDE_PREFIX option for flatbuffers_generate_headers (#5866)
40ba170c9 Fixed text in internals doc that implied structs can be root
cb4d0f72e [Swift] Object API support (#5826)
003e16405 [TS] Add Obj API (#5788)
21cf300f4 fix cpp usage markdown error (#5845)
9655e12d6 Upgraded swift implementation for grpc (#5843)
fb96fadc2 [C#] Fix nested structs and arrays in Object API (#5765)
408f11fbd [ts] Fix empty source/dest namespaces when reexporting. (#5841)
a83caf591 Improves performance for the swift library by using structs + a storage class (#5835)
925fab6b1 [Java][FlexBuffers] Optimize Map access (#5735)
d9fecc332 [CMake] : Add precompiled header support with FLATBUFFERS_ENABLE_PCH (#5827)
e9d453240 Added flatbuffers_generate_headers and flatbuffers_generate_binary_files cmake functions. (#5830)
c37c989ed Correct calculation of vector element size (#5831)
6b271b7ec Fix Clang-trunk warnings about special members deprecated in C++20. (#5829)
90f3b8e8c Fix `float_constant` definition in './doc/Grammar.md` (#5828)
3af735934 [csharp] flatc should generate a 'Create…' method for tables with struct field… (#5818)
c4231c3cb Updated doxyfile - added missing files (#5824)
9657df184 Update Grammar.md (#5820)
97ffc590e Include CPack only when explictly packaging (#5817)
8b52af65b [C++] Add max_depth and max_tables parameters to reflection::Verify (#5815)
9b034eee1 Fix interpretation of 'nan(number)' by the idl_parser (#5810)
3e9ac3cff [Scripts] Adds swift to generated code (#5806)
697147a2e updated maven build files
6df40a247 pre-tag version bump for 1.12
0dba63909 Removes the inner loop in the endtable check written tables (#5803)
0e3fdd0ee Escape characters in jsonschema descriptions (#5644)
45a2b07cb Remove `noexcept` qualifier copy-ctor of `union` type (#5800) (#5802)
d10c16314 Replace 'assert' by 'FLATBUFFERS_ASSERT' inside idl_parser.cpp (#5799)
35abb7f89 Add non-nullable modifier to return type of functions never returning null (#5797)
9954e09ab [C++] Generate code for vector force_align attribute. (#5796)
95a21327f rust: pub export the VectorIter type (#5736)
89b6183ee Fix Python min alignment
5a98d65e8 [Rust] Add gen-name-strings for Rust (#5757)
f73d205bc Removed assert that wasn't backwards compatible.
7c37abe92 [C#] add ObjectAPI Serialization Utility (#5785)
4749e77b0 Fixed docs on how to obtain parser error.
6ff189841 Added --filename-suffix and --filename-ext to flatc (#5778)
c9a30c9ca Fixed refractoring issue in reflection/generate_code.sh. Also, mv deletes the original file, so I don't need to clean it up manually in that case. (#5777)
8c02d17be Skip writing reflection_generated.h if not changed (#5776)
34305c4ce [Swift] Adds GRPC to Swift (#5758)
cd88e6b2a [Java][FlexBuffers] Abstract buffer access from ByteBuffer (#5743)
3ec7a53c6 Adds cocoapods and a readme of how to get the package (#5771)
6d44cede7 [snap] Fix versioning (#5727)
cc08c0835 [Python] Fixed potential allignment issue (#5768)
54f8b787c Fix memory leak on cpp object api (#5761)
17557f913 [Python] Fixed issue #5499 (#5764)
d54af8cd4 [C++] Use strong enum type for vectors when scoped-enums is on. (#5750)
173e10fdf [C#] support Json Serialization (#5752)
8f56990f6 FlexBuffers: C++: scalar-only typed vectors were not aligned.
6400c9b05 Bump Rust port to 0.6.1 (#5747)
7418d8587 [C#] support Object API (#5710)
c580fa284 Adds min and max, comments, and all of swift's keywords + fix docs (#5737)
f2a127230 Use VS 2017 and 2019 on CI, fix cast issue in dart_idl (#5740)
316d7c208 Creates a flatbuffers validation function + small fix (#5725)
47026ea6b Added the code to embed the binary schema to the source (--bfbs-gen-embed). (#5701)
3f677f241 [Java][FlexBuffers] Deprecate typed vector strings due to design flaw (#5722)
a593a11e5 [Go] Implements a SharedStrings function (#5733)
7cdfc8475 [Swift] Fix padding function overflow when bufSize is 0 (#5721)
bab2b0db4 Add vcpkg installation instructions (#5732)
89418eb84 [Dart] Fix deprecated field support, inf/nan (#5724)
9cadf05d8 [typescript] Size-prefixed root accessors not taking into account size prefix (#5717)
6da1cf79d [rust] Add use declarations to Rust-generated bindings for imported FB definitions (#5645)
bee1df96d [Go] Replace references to hardcoded ”Monster" etc with idiomatic go wherever possible (#5716)
01189d7ed [C++] Fix for printing of enum in case output_enum_identifiers=1. (#5706)
c4b2b0a25 [Swift] Support create long string (#5709)
a4b2884e4 Added create function for swift (#5707)
04d80f255 [Swift] Swift implementation 🎉🎉 (#5603)
55686100a Changed direct calls to strtod to use StringToNumber
718351831 Document JSON compatibility guarantees. (#5704)
d1b34f0f2 Add CMake 'generated_code' target to simplify resolution of build dependencies (#5697)
21b706196 (Optionally) add an additional suffix namespace to generated fbs files. (#5698)
35daaf83d [Java] Replace Table.UTF8_CHARSET with StandardCharsets.UTF_8 (#5696)
3b458f7a1 Rust: Temporarily disable 2 endianness unit tests (#5695)
a5d9d0f7d [C++17] Add Traits class for Tables and Factory function within it. (#5678)
3cd9b6434 Removed code_generators.cpp from library targets
355dfd48d [rust] Make enum names public (#5690)
bcd58a159 Correct inverted logic around include prefixes. (#5689)
a2c12900a Optimize Pack method using numpy (#5662)
901b89e73 [C++] Add Builder and Table typedefs (#5685)
31f879908 Minor doc updates: FlexBuffers C#, Discord, CppUsage.
8023d99e2 Upgrade rules_go (#5684)
b4154405d Fix --incompatible_load_cc_rules_from_bzl (#5683)
04c17c7a7 Add support for absl::string_view when available (#5682)
62ec7d52c [Bazel] Add support for compatible_with and restricted_to (#5681)
7de668053 CI: New Docker tests for Python with numpy (#5677)
3a70e0b30 Fixed struct initialization error on older versions of C#
9b1320135 Fixed warnings in FlexBuffers.java
5e3916050 Fixed out of date licenses on gRPC Python files.
c95755051 Removed test proto output.
44bf71988 Add flatc '--cpp_std' switch (#5656)
3e8f15df9 Fix for FlexBuffers FBT_VECTOR_STRING size bit-width.
602721a73 Added Check to VerifyAlignment (#5675)
13c05f4da Improve import handling for proto conversion (#5673)
ce3a1c43a [Dart] Fix prepare space for writeListInt64 and writeListUint64 (#5654)
aa75e5734 Make Rust constants public (#5659)
2790fee25 Add namespace qualification to union types (#5666)
eddebec1b Bugfix for Rust generation of union fields named with language keywords (#5592)
030fee36a wrap multiple statements in do {} while(!IsConstTrue(true)) (#5655)
f9724d1bd [gRPC] Uncomment MessageBuilder (#5658)
b20801ca4 Supress unsigned-integer-overflow for PaddingBytes (#5647)
a8e800bd7 Add --force-empty-vectors option (#5653)
d7530ae96 Fixed enum min/max values not properly escaped.
99d11e279 Split Bazel targets into multiple packages (#5640)
4fd8eb214 Remove a static_assert (#5643)
65f870357 Flatbuffers Python Object API (#5616)
75823cc27 [Clang 10]: definition of implicit copy constructor for 'TableKeyComparatoris deprecated #5649 (#5650)
58e279244 [docs]: add missing semicolon (#5648)
3c964e10a [GO] Fix support for enums with underscores and Unions with imported members (#5600)
c3c32ec94 Fix ambiguity of a type deduction in TEST_EQ macro if arguments have `enum class` type. (#5630)
075e8d676 Simplify declarations of x-macro FLATBUFFERS_TD (#5638)
bcf1bd5c9 read vtable size through ReadScalar() (#5636)
136d75fa6 Changed null checks in test. Removed verifier pointer usage (#5634)
091fa1fd1 Add testing of C++ with sanitizers (CI-Docker) (#5631)
ff3781dc2 add namespace prefix in FLATBUFFERS_MAX_BUFFER_SIZE (#5629)
6beb9f49c Support for python grpc - continuing the work from the pull request #4270 #4705 (#5613)
80988ea86 Removed idl_gen_general.cpp and move contents to code_generators.cpp (#5625)
0f2ff7eaa Lua cleanup (#5624)
dda095023 [C++] Adds basic schema evolution tests (#5611)
adbcbba5d [C++, C#, Java] Separated C# and Java generators into their own classes (#5618)
cbbd6aca0 add check for root_type specified for json schema generation (#5622)
405c64e07 [Rust] Bump smallvec version to 1.0 (#5621)
42c08cbca Ran src/clang-format-all.sh (#5617)
33d5dd9bd Improved pull request & clang-format instructions.
105dd528e Change monster_extra generation to use flatbuffers::unique_ptr (#5612)
f0f0efe7b [C++] Refactor to conform to Google C++ style guide (#5608)
e837d5a29 Fixed deprecated method in GRPC Java test.
9834ee978 Fixed Apache license not using canonical version.
44b2ab087 include/flatbuffers/base.h: fix no_sanitize issue with old clang (#5610)
46ae3f80a [C++, Java, C#, TypeScript, JavaScript] Skip generation of mutable union types (#5599)
7b38aa71e flatbuffers.h: fix documentation warning (#5607)
661bedd83 Add Lua FlatbufferBuilder Clean() method to enable reuseable builders (#5606)
8526e12d7 [Kotlin] Fix union vector accessor after change in Java API (#5605)
3c7b660d6 [flatc] Remove an always true condition for flexbuffers (#5604)
964365ba6 [Go] Add UnPackTo functions (#5598)
32254b7ac [Go] Object API support (#5339)
521e255ad Rust: Add idiomatic iterator for Vector type (#5579)
1b85292fd Fix typos in comments (#5590)
480815447 C++ verifier for evolved union fields should return true (#5586)
8d5e424c6 Add ByteBuffer copy for vector of bytes in Java (#5587)
b4774d235 Rust: Fix Copy and Clone impls for a few generic types (#5577)
26f238c24 Add `--clean-first` to the cmake-build command (travis) (#5574)
e93c8c46e Fix Follow implementation for bool (#5554)
e21516b9d Fix issue #5557 (#5573)
fbc11e8ae Avoid intentional unsigned integer overflow getting caught by sanitizers (#5572)
e9d29c21a Python: Add forceDefaults opt to python Builder (#5564)
8bfafc76d Java: Don't annotate vector-of-tables item getters with @nullable. (#5562)
df3e8bf4a Fixed warnings generated by recent JSON sorting feature.
5665cfe49 [Java] byte buffer factory returned buffer capcity is used instead of the requested size (#5558)
5797540ed #5544 Fix of Array of table is not sorted if Create<type>Direct() is used (#5546)
7f1af7cb0 Fix build with gcc version 7.4.0 (#5570)
32f47ad24 Fixed JSON parser not sorting vectors of tables/structs with key.
842f672ba [FlexBuffers][Java] Cache size of Sized objects in FlexBuffers (#5551)
d4cae0a62 Fix issue #5542 (#5543)
f1147f65b Fixed Android STLPort related error.
69d3fec48 Fix namespaced struct/field name collision detection (#5540) (#5545)
cfb4ecf6f [flac] Add FlexBuffers option for generating data (#5519)
a92039687 Update Rust versions under test from 1.30.1 to 1.37.0 (#5538)
625338d09 Adds XOPEN_SOURCE for PATH_MAX and POSIX 1993 for stat (#5529)
3f8ce99c5 [FlexBuffers][Java] Add override Key::toString (#5533)
0798b7b69 [FlexBuffers][Java] Fix wrong access to a string using Reference::asString(). (#5532)
cbdf82e2f Fix Mutate() methods of Array<scalar/struct> (override 5508) (#5526)
e365c502f Java: Added access object for vector of struct and vector of tables. (#5233)
97f3aa917 Fixed DetachedBuffer self move assignment (#5521)
2f5bb2eec Fix buildifier warnings found in new bazel (#5517)
917687c7a Fixed Reflection Verifier not handling vectors of unions.
f9277e691 Fixed GenerateText not handling vectors of unions.
2706381ee Add element size parameter to __vector_as_arraysegment [c#] (#5512)
b5560fcd5 [Java][FlexBuffers] Improve documentation for FlexBuffers in Java. (#5506)
782b865c5 Annotate getters with @Pure when --java-checkerframework is specified. (#5510)
3bfc86eaf [Dart]fix: segment fault with empty namespace when generating dart file (#5507)
c0282873f Rust: Fixed cargo clippy on non-generated code (#5485)
4b870aca9 [Javascript] Fix syntax error for signed enum (#5503)
d0e3870c0 [C#] Fix retrieving enumeration vectors as arrays (#5457)
fb25eb87f Doc typo fixes (#5505)
cb35d3a0e Use all of the available space in the buffer returned by ByteBufferFactory to allow the factory to keep a pool of larger than initialsize sized buffers. (#5500)
8e6cabb31 [FlexBuffers][Java] Implementation of FlexBuffers API (#5476)
bd31dd242 Clarified value reuse in FlexBuffers
65b67d213 Fixed test build invocation of arrays_test.fbs
1fbb71132 FlexBuffers: allow any values to be shared.
cd75a3658 Android: remove app_dummy() calls
ec6b0bf29 Fixed STLPort Android compile error
c11b5d744 [bugfix]flexbuffers isvector bugfix (#5488)
4525c91be Fix incorrect padding in arrays of structs (Issue #5484) (#5491)
b97b342f5 Fixed missing generated code.
c1058a903 C++ IDL generation adds superfluous semicolon in GenTablePost, causing (#5483)
303044934 [go]add Name() for ForceCodec interface (#5486)
a2485d4ec reflection: check for valid union enum value during object verification (#5475)
a20e71ac9 has_method support for primitive fields in java runtime. Changed: idl.h, FlatBufferBuilder.java , idl_gen_general.cpp, idl_parser.cpp, flatc.cpp (#5468)
Change-Id: I836f4b43e6818bb16425a87899e6234ac86242aa
git-subtree-dir: third_party/flatbuffers
git-subtree-split: d6a8dbd26ff08a8868e0d0c1b4b67d31b40e4a7f
diff --git a/include/flatbuffers/base.h b/include/flatbuffers/base.h
index d98da13..085099a 100644
--- a/include/flatbuffers/base.h
+++ b/include/flatbuffers/base.h
@@ -46,14 +46,17 @@
#include <iterator>
#include <memory>
+#if defined(__unix__) && !defined(FLATBUFFERS_LOCALE_INDEPENDENT)
+ #include <unistd.h>
+#endif
+
#ifdef _STLPORT_VERSION
#define FLATBUFFERS_CPP98_STL
#endif
-#ifndef FLATBUFFERS_CPP98_STL
- #include <functional>
-#endif
-#include "flatbuffers/stl_emulation.h"
+#ifdef __ANDROID__
+ #include <android/api-level.h>
+#endif
#if defined(__ICCARM__)
#include <intrinsics.h>
@@ -99,7 +102,7 @@
#if !defined(__clang__) && \
defined(__GNUC__) && \
(__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__ < 40600)
- // Backwards compatability for g++ 4.4, and 4.5 which don't have the nullptr
+ // Backwards compatibility for g++ 4.4, and 4.5 which don't have the nullptr
// and constexpr keywords. Note the __clang__ check is needed, because clang
// presents itself as an older GNUC compiler.
#ifndef nullptr_t
@@ -140,7 +143,7 @@
#endif // !defined(FLATBUFFERS_LITTLEENDIAN)
#define FLATBUFFERS_VERSION_MAJOR 1
-#define FLATBUFFERS_VERSION_MINOR 11
+#define FLATBUFFERS_VERSION_MINOR 12
#define FLATBUFFERS_VERSION_REVISION 0
#define FLATBUFFERS_STRING_EXPAND(X) #X
#define FLATBUFFERS_STRING(X) FLATBUFFERS_STRING_EXPAND(X)
@@ -154,10 +157,12 @@
defined(__clang__)
#define FLATBUFFERS_FINAL_CLASS final
#define FLATBUFFERS_OVERRIDE override
+ #define FLATBUFFERS_EXPLICIT_CPP11 explicit
#define FLATBUFFERS_VTABLE_UNDERLYING_TYPE : flatbuffers::voffset_t
#else
#define FLATBUFFERS_FINAL_CLASS
#define FLATBUFFERS_OVERRIDE
+ #define FLATBUFFERS_EXPLICIT_CPP11
#define FLATBUFFERS_VTABLE_UNDERLYING_TYPE
#endif
@@ -165,13 +170,16 @@
(!defined(__GNUC__) || (__GNUC__ * 100 + __GNUC_MINOR__ >= 406)) || \
(defined(__cpp_constexpr) && __cpp_constexpr >= 200704)
#define FLATBUFFERS_CONSTEXPR constexpr
+ #define FLATBUFFERS_CONSTEXPR_CPP11 constexpr
+ #define FLATBUFFERS_CONSTEXPR_DEFINED
#else
#define FLATBUFFERS_CONSTEXPR const
+ #define FLATBUFFERS_CONSTEXPR_CPP11
#endif
#if (defined(__cplusplus) && __cplusplus >= 201402L) || \
(defined(__cpp_constexpr) && __cpp_constexpr >= 201304)
- #define FLATBUFFERS_CONSTEXPR_CPP14 FLATBUFFERS_CONSTEXPR
+ #define FLATBUFFERS_CONSTEXPR_CPP14 FLATBUFFERS_CONSTEXPR_CPP11
#else
#define FLATBUFFERS_CONSTEXPR_CPP14
#endif
@@ -194,12 +202,22 @@
#define FLATBUFFERS_DELETE_FUNC(func) private: func;
#endif
+// Check if we can use template aliases
+// Not possible if Microsoft Compiler before 2012
+// Possible is the language feature __cpp_alias_templates is defined well
+// Or possible if the C++ std is C+11 or newer
+#if (defined(_MSC_VER) && _MSC_VER > 1700 /* MSVC2012 */) \
+ || (defined(__cpp_alias_templates) && __cpp_alias_templates >= 200704) \
+ || (defined(__cplusplus) && __cplusplus >= 201103L)
+ #define FLATBUFFERS_TEMPLATES_ALIASES
+#endif
+
#ifndef FLATBUFFERS_HAS_STRING_VIEW
// Only provide flatbuffers::string_view if __has_include can be used
// to detect a header that provides an implementation
#if defined(__has_include)
// Check for std::string_view (in c++17)
- #if __has_include(<string_view>) && (__cplusplus >= 201606 || _HAS_CXX17)
+ #if __has_include(<string_view>) && (__cplusplus >= 201606 || (defined(_HAS_CXX17) && _HAS_CXX17))
#include <string_view>
namespace flatbuffers {
typedef std::string_view string_view;
@@ -212,6 +230,13 @@
typedef std::experimental::string_view string_view;
}
#define FLATBUFFERS_HAS_STRING_VIEW 1
+ // Check for absl::string_view
+ #elif __has_include("absl/strings/string_view.h")
+ #include "absl/strings/string_view.h"
+ namespace flatbuffers {
+ typedef absl::string_view string_view;
+ }
+ #define FLATBUFFERS_HAS_STRING_VIEW 1
#endif
#endif // __has_include
#endif // !FLATBUFFERS_HAS_STRING_VIEW
@@ -229,10 +254,8 @@
#ifndef FLATBUFFERS_LOCALE_INDEPENDENT
// Enable locale independent functions {strtof_l, strtod_l,strtoll_l, strtoull_l}.
- // They are part of the POSIX-2008 but not part of the C/C++ standard.
- // GCC/Clang have definition (_XOPEN_SOURCE>=700) if POSIX-2008.
#if ((defined(_MSC_VER) && _MSC_VER >= 1800) || \
- (defined(_XOPEN_SOURCE) && (_XOPEN_SOURCE>=700)))
+ (defined(_XOPEN_VERSION) && (_XOPEN_VERSION>=700)) && (!defined(__ANDROID_API__) || (defined(__ANDROID_API__) && (__ANDROID_API__>=21))))
#define FLATBUFFERS_LOCALE_INDEPENDENT 1
#else
#define FLATBUFFERS_LOCALE_INDEPENDENT 0
@@ -242,7 +265,7 @@
// Suppress Undefined Behavior Sanitizer (recoverable only). Usage:
// - __supress_ubsan__("undefined")
// - __supress_ubsan__("signed-integer-overflow")
-#if defined(__clang__)
+#if defined(__clang__) && (__clang_major__ > 3 || (__clang_major__ == 3 && __clang_minor__ >=7))
#define __supress_ubsan__(type) __attribute__((no_sanitize(type)))
#elif defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__ >= 409)
#define __supress_ubsan__(type) __attribute__((no_sanitize_undefined))
@@ -296,12 +319,13 @@
typedef uintmax_t largest_scalar_t;
// In 32bits, this evaluates to 2GB - 1
-#define FLATBUFFERS_MAX_BUFFER_SIZE ((1ULL << (sizeof(soffset_t) * 8 - 1)) - 1)
+#define FLATBUFFERS_MAX_BUFFER_SIZE ((1ULL << (sizeof(::flatbuffers::soffset_t) * 8 - 1)) - 1)
// We support aligning the contents of buffers up to this size.
#define FLATBUFFERS_MAX_ALIGNMENT 16
#if defined(_MSC_VER)
+ #pragma warning(disable: 4351) // C4351: new behavior: elements of array ... will be default initialized
#pragma warning(push)
#pragma warning(disable: 4127) // C4127: conditional expression is constant
#endif
@@ -330,22 +354,20 @@
if (sizeof(T) == 1) { // Compile-time if-then's.
return t;
} else if (sizeof(T) == 2) {
- union { T t; uint16_t i; } u;
- u.t = t;
+ union { T t; uint16_t i; } u = { t };
u.i = FLATBUFFERS_BYTESWAP16(u.i);
return u.t;
} else if (sizeof(T) == 4) {
- union { T t; uint32_t i; } u;
- u.t = t;
+ union { T t; uint32_t i; } u = { t };
u.i = FLATBUFFERS_BYTESWAP32(u.i);
return u.t;
} else if (sizeof(T) == 8) {
- union { T t; uint64_t i; } u;
- u.t = t;
+ union { T t; uint64_t i; } u = { t };
u.i = FLATBUFFERS_BYTESWAP64(u.i);
return u.t;
} else {
FLATBUFFERS_ASSERT(0);
+ return t;
}
}
@@ -369,6 +391,13 @@
return EndianScalar(*reinterpret_cast<const T *>(p));
}
+// See https://github.com/google/flatbuffers/issues/5950
+
+#if (FLATBUFFERS_GCC >= 100000) && (FLATBUFFERS_GCC < 110000)
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wstringop-overflow"
+#endif
+
template<typename T>
// UBSAN: C++ aliasing type rules, see std::bit_cast<> for details.
__supress_ubsan__("alignment")
@@ -381,9 +410,14 @@
*reinterpret_cast<uoffset_t *>(p) = EndianScalar(t.o);
}
+#if (FLATBUFFERS_GCC >= 100000) && (FLATBUFFERS_GCC < 110000)
+ #pragma GCC diagnostic pop
+#endif
+
// Computes how many bytes you'd have to pad to be able to write an
// "scalar_size" scalar if the buffer had grown to "buf_size" (downwards in
// memory).
+__supress_ubsan__("unsigned-integer-overflow")
inline size_t PaddingBytes(size_t buf_size, size_t scalar_size) {
return ((~buf_size) + 1) & (scalar_size - 1);
}
diff --git a/include/flatbuffers/code_generators.h b/include/flatbuffers/code_generators.h
index 0bcec91..d64ab03 100644
--- a/include/flatbuffers/code_generators.h
+++ b/include/flatbuffers/code_generators.h
@@ -19,6 +19,7 @@
#include <map>
#include <sstream>
+
#include "flatbuffers/idl.h"
namespace flatbuffers {
@@ -60,7 +61,7 @@
}
// Appends the given text to the generated code as well as a newline
- // character. Any text within {{ and }} delimeters is replaced by values
+ // character. Any text within {{ and }} delimiters is replaced by values
// previously stored in the CodeWriter by calling SetValue above. The newline
// will be suppressed if the text ends with the \\ character.
void operator+=(std::string text);
@@ -75,6 +76,8 @@
if (cur_ident_lvl_) cur_ident_lvl_--;
}
+ void SetPadding(const std::string &padding) { pad_ = padding; }
+
private:
std::map<std::string, std::string> value_map_;
std::stringstream stream_;
@@ -93,16 +96,20 @@
static std::string NamespaceDir(const Parser &parser, const std::string &path,
const Namespace &ns);
+ std::string GeneratedFileName(const std::string &path,
+ const std::string &file_name,
+ const IDLOptions &options) const;
+
protected:
BaseGenerator(const Parser &parser, const std::string &path,
- const std::string &file_name,
- std::string qualifying_start,
- std::string qualifying_separator)
+ const std::string &file_name, std::string qualifying_start,
+ std::string qualifying_separator, std::string default_extension)
: parser_(parser),
path_(path),
file_name_(file_name),
qualifying_start_(qualifying_start),
- qualifying_separator_(qualifying_separator) {}
+ qualifying_separator_(qualifying_separator),
+ default_extension_(default_extension) {}
virtual ~BaseGenerator() {}
// No copy/assign.
@@ -138,6 +145,7 @@
const std::string &file_name_;
const std::string qualifying_start_;
const std::string qualifying_separator_;
+ const std::string default_extension_;
};
struct CommentConfig {
diff --git a/include/flatbuffers/flatbuffers.h b/include/flatbuffers/flatbuffers.h
index 1a250cd..8683832 100644
--- a/include/flatbuffers/flatbuffers.h
+++ b/include/flatbuffers/flatbuffers.h
@@ -18,9 +18,14 @@
#define FLATBUFFERS_H_
#include "flatbuffers/base.h"
+#include "flatbuffers/stl_emulation.h"
+
+#ifndef FLATBUFFERS_CPP98_STL
+ #include <functional>
+#endif
#if defined(FLATBUFFERS_NAN_DEFAULTS)
-#include <cmath>
+# include <cmath>
#endif
namespace flatbuffers {
@@ -43,6 +48,20 @@
}
#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 {
@@ -203,11 +222,10 @@
const uint8_t *data_;
};
-template<typename Iterator> struct VectorReverseIterator :
- public std::reverse_iterator<Iterator> {
-
- explicit VectorReverseIterator(Iterator iter) :
- std::reverse_iterator<Iterator>(iter) {}
+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);
@@ -277,10 +295,14 @@
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); }
+ 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_reverse_iterator rend() const {
+ return const_reverse_iterator(begin() - 1);
+ }
const_iterator cbegin() const { return begin(); }
@@ -348,6 +370,7 @@
// 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);
@@ -378,6 +401,7 @@
private:
VectorOfAny(const VectorOfAny &);
+ VectorOfAny &operator=(const VectorOfAny &);
};
#ifndef FLATBUFFERS_CPP98_STL
@@ -402,22 +426,36 @@
// This is used as a helper type for accessing arrays.
template<typename T, uint16_t length> class Array {
- public:
- typedef VectorIterator<T, typename IndirectHelper<T>::return_type>
- const_iterator;
- typedef VectorReverseIterator<const_iterator> const_reverse_iterator;
+ 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;
- typedef typename IndirectHelper<T>::return_type return_type;
+ 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<T>::Read(Data(), i);
+ 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()); }
@@ -432,22 +470,20 @@
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.
- void Mutate(uoffset_t i, const T &val) {
- FLATBUFFERS_ASSERT(i < size());
- WriteScalar(data() + i, val);
- }
-
// Get a mutable pointer to elements inside this array.
- // @note This method should be only used to mutate arrays of structs followed
- // by a @p Mutate operation. For primitive types use @p Mutate directly.
+ // 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.
- T *GetMutablePointer(uoffset_t i) const {
+ 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_; }
@@ -457,7 +493,48 @@
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.
@@ -475,8 +552,58 @@
// 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,
@@ -504,16 +631,24 @@
// Convenience function to get std::string from a String returning an empty
// string on null pointer.
-static inline std::string GetString(const String * str) {
+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) {
+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 {
@@ -547,9 +682,9 @@
// 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) {
+ 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);
@@ -563,13 +698,9 @@
return new uint8_t[size];
}
- void deallocate(uint8_t *p, size_t) FLATBUFFERS_OVERRIDE {
- delete[] p;
- }
+ void deallocate(uint8_t *p, size_t) FLATBUFFERS_OVERRIDE { delete[] p; }
- static void dealloc(void *p, size_t) {
- delete[] static_cast<uint8_t *>(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,
@@ -582,18 +713,19 @@
}
inline void Deallocate(Allocator *allocator, uint8_t *p, size_t size) {
- if (allocator) allocator->deallocate(p, size);
- else DefaultAllocator().deallocate(p, 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);
+ 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
@@ -638,6 +770,8 @@
#if !defined(FLATBUFFERS_CPP98_STL)
// clang-format on
DetachedBuffer &operator=(DetachedBuffer &&other) {
+ if (this == &other) return *this;
+
destroy();
allocator_ = other.allocator_;
@@ -694,7 +828,7 @@
#endif // !defined(FLATBUFFERS_CPP98_STL)
// clang-format on
-protected:
+ protected:
Allocator *allocator_;
bool own_allocator_;
uint8_t *buf_;
@@ -726,10 +860,8 @@
// 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)
+ 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),
@@ -745,15 +877,15 @@
#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_) {
+ // 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_
@@ -797,9 +929,7 @@
clear_scratch();
}
- void clear_scratch() {
- scratch_ = buf_;
- }
+ void clear_scratch() { scratch_ = buf_; }
void clear_allocator() {
if (own_allocator_ && allocator_) { delete allocator_; }
@@ -858,7 +988,7 @@
Allocator *get_custom_allocator() { return allocator_; }
uoffset_t size() const {
- return static_cast<uoffset_t>(reserved_ - (cur_ - buf_));
+ return static_cast<uoffset_t>(reserved_ - static_cast<size_t>(cur_ - buf_));
}
uoffset_t scratch_size() const {
@@ -952,8 +1082,8 @@
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_ +=
+ (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_,
@@ -978,13 +1108,13 @@
// 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();
+ 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();
+ return v.empty() ? reinterpret_cast<T *>(&t) : &v.front();
}
/// @endcond
@@ -1011,11 +1141,10 @@
/// 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>())
+ 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),
@@ -1110,6 +1239,14 @@
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(); }
@@ -1118,8 +1255,8 @@
/// @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() {
+ FLATBUFFERS_ATTRIBUTE(deprecated("use Release() instead"))
+ DetachedBuffer ReleaseBufferPointer() {
Finished();
return buf_.release();
}
@@ -1132,13 +1269,14 @@
}
/// @brief Get the released pointer to the serialized buffer.
- /// @param The size of the memory block containing
+ /// @param size The size of the memory block containing
/// the serialized `FlatBuffer`.
- /// @param The offset from the released pointer where the finished
+ /// @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..
+ /// @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);
@@ -1149,7 +1287,7 @@
/// 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() {
+ size_t GetBufferMinAlignment() const {
Finished();
return minalign_;
}
@@ -1167,12 +1305,13 @@
/// @brief In order to save space, fields that are set to their default value
/// don't get serialized into the buffer.
- /// @param[in] bool fd When set to `true`, always serializes default values that are set.
- /// Optional fields which are not set explicitly, will still not be serialized.
+ /// @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] bool dedup When set to `true`, dedup vtables.
+ /// @param[in] dedup When set to `true`, dedup vtables.
void DedupVtables(bool dedup) { dedup_vtables_ = dedup; }
/// @cond FLATBUFFERS_INTERNAL
@@ -1232,6 +1371,11 @@
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));
@@ -1326,7 +1470,7 @@
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 = *vt2;
+ 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);
@@ -1536,6 +1680,9 @@
// 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));
@@ -1655,14 +1802,14 @@
extern T Pack(const S &);
std::vector<T> vv(len);
std::transform(v, v + len, vv.begin(), Pack);
- return CreateVectorOfStructs<T>(vv.data(), vv.size());
+ 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] f A function that takes the current iteration 0..vector_size-1
+ /// @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.
@@ -1702,7 +1849,7 @@
/// @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
+ /// @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.
@@ -1716,7 +1863,7 @@
/// `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
+ /// @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.
@@ -1732,15 +1879,15 @@
return a.KeyCompareLessThan(&b);
}
- private:
- StructKeyComparator &operator=(const StructKeyComparator &);
+ 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
+ /// @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.
@@ -1753,7 +1900,7 @@
/// `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
+ /// @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.
@@ -1792,13 +1939,14 @@
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));
+ 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));
@@ -1807,7 +1955,7 @@
vector_downward &buf_;
private:
- TableKeyComparator &operator=(const TableKeyComparator &);
+ FLATBUFFERS_DELETE_FUNC(TableKeyComparator &operator=(const TableKeyComparator &other))
};
/// @endcond
@@ -1873,12 +2021,12 @@
}
template<typename T>
- Offset<Vector<const T*>> CreateUninitializedVectorOfStructs(size_t len, T **buf) {
+ 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.
@@ -1927,8 +2075,7 @@
buf_.swap_allocator(other.buf_);
}
-protected:
-
+ protected:
// You shouldn't really be copying instances of this class.
FlatBufferBuilder(const FlatBufferBuilder &);
FlatBufferBuilder &operator=(const FlatBufferBuilder &);
@@ -1981,8 +2128,8 @@
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());
+ return StringLessThan(stra->data(), stra->size(), strb->data(),
+ strb->size());
}
const vector_downward *buf_;
};
@@ -2046,13 +2193,15 @@
/// 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) {
+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) {
+inline bool BufferHasIdentifier(const void *buf, const char *identifier,
+ bool size_prefixed = false) {
return strncmp(GetBufferIdentifier(buf, size_prefixed), identifier,
FlatBufferBuilder::kFileIdentifierLength) == 0;
}
@@ -2069,8 +2218,7 @@
num_tables_(0),
max_tables_(_max_tables),
upper_bound_(0),
- check_alignment_(_check_alignment)
- {
+ check_alignment_(_check_alignment) {
FLATBUFFERS_ASSERT(size_ < FLATBUFFERS_MAX_BUFFER_SIZE);
}
@@ -2101,7 +2249,7 @@
}
template<typename T> bool VerifyAlignment(size_t elem) const {
- return (elem & (sizeof(T) - 1)) == 0 || !check_alignment_;
+ return Check((elem & (sizeof(T) - 1)) == 0 || !check_alignment_);
}
// Verify a range indicated by sizeof(T).
@@ -2109,13 +2257,18 @@
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 {
+ 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));
}
@@ -2138,16 +2291,15 @@
// 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.
+ 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 {
+ 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;
@@ -2182,11 +2334,12 @@
return true;
}
- bool VerifyTableStart(const uint8_t *table) {
+ __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 substraction unsigned always
+ // 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.
@@ -2197,9 +2350,8 @@
template<typename T>
bool VerifyBufferFromStart(const char *identifier, size_t start) {
- if (identifier &&
- (size_ < 2 * sizeof(flatbuffers::uoffset_t) ||
- !BufferHasIdentifier(buf_ + start, identifier))) {
+ if (identifier && !Check((size_ >= 2 * sizeof(flatbuffers::uoffset_t) &&
+ BufferHasIdentifier(buf_ + start, identifier)))) {
return false;
}
@@ -2331,6 +2483,12 @@
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];
};
@@ -2375,12 +2533,26 @@
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);
@@ -2443,12 +2615,24 @@
// class by pointing to existing data only
Table();
Table(const Table &other);
+ Table &operator=(const Table &);
uint8_t data_[1];
};
-template<typename T> void FlatBufferBuilder::Required(Offset<T> table,
- voffset_t field) {
+// 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.
@@ -2495,7 +2679,9 @@
}
/// @brief This return the prefixed size of a FlatBuffer.
-inline uoffset_t GetPrefixedSize(const uint8_t* buf){ return ReadScalar<uoffset_t>(buf); }
+inline uoffset_t GetPrefixedSize(const uint8_t *buf) {
+ return ReadScalar<uoffset_t>(buf);
+}
// Base class for native objects (FlatBuffer data de-serialized into native
// C++ data structures).
@@ -2622,10 +2808,13 @@
// clang-format on
// Basic type info cost just 16bits per field!
+// We're explicitly defining the signedness since the signedness of integer
+// bitfields is otherwise implementation-defined and causes warnings on older
+// GCC compilers.
struct TypeCode {
- uint16_t base_type : 4; // ElementaryType
- uint16_t is_vector : 1;
- int16_t sequence_ref : 11; // Index into type_refs below, or -1 for none.
+ 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.
};
static_assert(sizeof(TypeCode) == 2, "TypeCode");
@@ -2638,10 +2827,11 @@
struct TypeTable {
SequenceType st;
size_t num_elems; // of type_codes, values, names (but not type_refs).
- const TypeCode *type_codes; // num_elems count
+ const TypeCode *type_codes; // num_elems count
const TypeFunction *type_refs; // less than num_elems entries (see TypeCode).
+ const int16_t *array_sizes; // less than num_elems entries (see TypeCode).
const int64_t *values; // Only set for non-consecutive enum/union or structs.
- const char * const *names; // Only set if compiled with --reflect-names.
+ const char *const *names; // Only set if compiled with --reflect-names.
};
// String which identifies the current version of FlatBuffers.
diff --git a/include/flatbuffers/flatc.h b/include/flatbuffers/flatc.h
index f2765d2..5e2709e 100644
--- a/include/flatbuffers/flatc.h
+++ b/include/flatbuffers/flatc.h
@@ -14,18 +14,22 @@
* limitations under the License.
*/
+#ifndef FLATBUFFERS_FLATC_H_
+#define FLATBUFFERS_FLATC_H_
+
#include <functional>
#include <limits>
#include <string>
+
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
-#ifndef FLATC_H_
-# define FLATC_H_
-
namespace flatbuffers {
+extern void LogCompilerWarn(const std::string &warn);
+extern void LogCompilerError(const std::string &err);
+
class FlatCompiler {
public:
// Output generator for the various programming languages and formats we
@@ -93,4 +97,4 @@
} // namespace flatbuffers
-#endif // FLATC_H_
+#endif // FLATBUFFERS_FLATC_H_
diff --git a/include/flatbuffers/flexbuffers.h b/include/flatbuffers/flexbuffers.h
index 7cba5b7..a45d14b 100644
--- a/include/flatbuffers/flexbuffers.h
+++ b/include/flatbuffers/flexbuffers.h
@@ -65,7 +65,9 @@
FBT_VECTOR_UINT = 12,
FBT_VECTOR_FLOAT = 13,
FBT_VECTOR_KEY = 14,
- FBT_VECTOR_STRING = 15,
+ // DEPRECATED, use FBT_VECTOR or FBT_VECTOR_KEY instead.
+ // Read test.cpp/FlexBuffersDeprecatedTest() for details on why.
+ FBT_VECTOR_STRING_DEPRECATED = 15,
FBT_VECTOR_INT2 = 16, // Typed tuple (no type table, no size field).
FBT_VECTOR_UINT2 = 17,
FBT_VECTOR_FLOAT2 = 18,
@@ -88,7 +90,7 @@
}
inline bool IsTypedVector(Type t) {
- return (t >= FBT_VECTOR_INT && t <= FBT_VECTOR_STRING) ||
+ return (t >= FBT_VECTOR_INT && t <= FBT_VECTOR_STRING_DEPRECATED) ||
t == FBT_VECTOR_BOOL;
}
@@ -212,26 +214,40 @@
uint8_t byte_width_;
};
-// Stores size in `byte_width_` bytes before data_ pointer.
+// Object that has a size, obtained either from size prefix, or elsewhere.
class Sized : public Object {
public:
- Sized(const uint8_t *data, uint8_t byte_width) : Object(data, byte_width) {}
- size_t size() const {
+ // Size prefix.
+ Sized(const uint8_t *data, uint8_t byte_width)
+ : Object(data, byte_width), size_(read_size()) {}
+ // Manual size.
+ Sized(const uint8_t *data, uint8_t byte_width, size_t sz)
+ : Object(data, byte_width), size_(sz) {}
+ size_t size() const { return size_; }
+ // Access size stored in `byte_width_` bytes before data_ pointer.
+ size_t read_size() const {
return static_cast<size_t>(ReadUInt64(data_ - byte_width_, byte_width_));
}
+
+ protected:
+ size_t size_;
};
class String : public Sized {
public:
+ // Size prefix.
String(const uint8_t *data, uint8_t byte_width) : Sized(data, byte_width) {}
+ // Manual size.
+ String(const uint8_t *data, uint8_t byte_width, size_t sz)
+ : Sized(data, byte_width, sz) {}
size_t length() const { return size(); }
const char *c_str() const { return reinterpret_cast<const char *>(data_); }
- std::string str() const { return std::string(c_str(), length()); }
+ std::string str() const { return std::string(c_str(), size()); }
static String EmptyString() {
- static const uint8_t empty_string[] = { 0 /*len*/, 0 /*terminator*/ };
- return String(empty_string + 1, 1);
+ static const char *empty_string = "";
+ return String(reinterpret_cast<const uint8_t *>(empty_string), 1, 0);
}
bool IsTheEmptyString() const { return data_ == EmptyString().data_; }
};
@@ -279,6 +295,8 @@
Type ElementType() { return type_; }
+ friend Reference;
+
private:
Type type_;
@@ -339,16 +357,22 @@
template<typename T>
void AppendToString(std::string &s, T &&v, bool keys_quoted) {
- s += "[ ";
- for (size_t i = 0; i < v.size(); i++) {
- if (i) s += ", ";
- v[i].ToString(true, keys_quoted, s);
- }
- s += " ]";
+ s += "[ ";
+ for (size_t i = 0; i < v.size(); i++) {
+ if (i) s += ", ";
+ v[i].ToString(true, keys_quoted, s);
+ }
+ s += " ]";
}
class Reference {
public:
+ Reference()
+ : data_(nullptr),
+ parent_width_(0),
+ byte_width_(BIT_WIDTH_8),
+ type_(FBT_NULL) {}
+
Reference(const uint8_t *data, uint8_t parent_width, uint8_t byte_width,
Type type)
: data_(data),
@@ -378,15 +402,19 @@
bool IsString() const { return type_ == FBT_STRING; }
bool IsKey() const { return type_ == FBT_KEY; }
bool IsVector() const { return type_ == FBT_VECTOR || type_ == FBT_MAP; }
+ bool IsUntypedVector() const { return type_ == FBT_VECTOR; }
bool IsTypedVector() const { return flexbuffers::IsTypedVector(type_); }
- bool IsFixedTypedVector() const { return flexbuffers::IsFixedTypedVector(type_); }
- bool IsAnyVector() const { return (IsTypedVector() || IsFixedTypedVector() || IsVector());}
+ bool IsFixedTypedVector() const {
+ return flexbuffers::IsFixedTypedVector(type_);
+ }
+ bool IsAnyVector() const {
+ return (IsTypedVector() || IsFixedTypedVector() || IsVector());
+ }
bool IsMap() const { return type_ == FBT_MAP; }
bool IsBlob() const { return type_ == FBT_BLOB; }
-
bool AsBool() const {
return (type_ == FBT_BOOL ? ReadUInt64(data_, parent_width_)
- : AsUInt64()) != 0;
+ : AsUInt64()) != 0;
}
// Reads any type as a int64_t. Never fails, does most sensible conversion.
@@ -464,7 +492,11 @@
case FBT_INDIRECT_UINT:
return static_cast<double>(ReadUInt64(Indirect(), byte_width_));
case FBT_NULL: return 0.0;
- case FBT_STRING: return strtod(AsString().c_str(), nullptr);
+ case FBT_STRING: {
+ double d;
+ flatbuffers::StringToNumber(AsString().c_str(), &d);
+ return d;
+ }
case FBT_VECTOR: return static_cast<double>(AsVector().size());
case FBT_BOOL:
return static_cast<double>(ReadUInt64(data_, parent_width_));
@@ -477,17 +509,22 @@
float AsFloat() const { return static_cast<float>(AsDouble()); }
const char *AsKey() const {
- if (type_ == FBT_KEY) {
+ if (type_ == FBT_KEY || type_ == FBT_STRING) {
return reinterpret_cast<const char *>(Indirect());
} else {
return "";
}
}
- // This function returns the empty string if you try to read a not-string.
+ // This function returns the empty string if you try to read something that
+ // is not a string or key.
String AsString() const {
if (type_ == FBT_STRING) {
return String(Indirect(), byte_width_);
+ } else if (type_ == FBT_KEY) {
+ auto key = Indirect();
+ return String(key, byte_width_,
+ strlen(reinterpret_cast<const char *>(key)));
} else {
return String::EmptyString();
}
@@ -549,7 +586,8 @@
AppendToString<FixedTypedVector>(s, AsFixedTypedVector(), keys_quoted);
} else if (IsBlob()) {
auto blob = AsBlob();
- flatbuffers::EscapeString(reinterpret_cast<const char*>(blob.data()), blob.size(), &s, true, false);
+ flatbuffers::EscapeString(reinterpret_cast<const char *>(blob.data()),
+ blob.size(), &s, true, false);
} else {
s += "(?)";
}
@@ -577,8 +615,18 @@
TypedVector AsTypedVector() const {
if (IsTypedVector()) {
- return TypedVector(Indirect(), byte_width_,
- ToTypedVectorElementType(type_));
+ auto tv =
+ TypedVector(Indirect(), byte_width_, ToTypedVectorElementType(type_));
+ if (tv.type_ == FBT_STRING) {
+ // These can't be accessed as strings, since we don't know the bit-width
+ // of the size field, see the declaration of
+ // FBT_VECTOR_STRING_DEPRECATED above for details.
+ // We change the type here to be keys, which are a subtype of strings,
+ // and will ignore the size field. This will truncate strings with
+ // embedded nulls.
+ tv.type_ = FBT_KEY;
+ }
+ return tv;
} else {
return TypedVector::EmptyTypedVector();
}
@@ -723,9 +771,15 @@
template<> inline int64_t Reference::As<int64_t>() const { return AsInt64(); }
template<> inline uint8_t Reference::As<uint8_t>() const { return AsUInt8(); }
-template<> inline uint16_t Reference::As<uint16_t>() const { return AsUInt16(); }
-template<> inline uint32_t Reference::As<uint32_t>() const { return AsUInt32(); }
-template<> inline uint64_t Reference::As<uint64_t>() const { return AsUInt64(); }
+template<> inline uint16_t Reference::As<uint16_t>() const {
+ return AsUInt16();
+}
+template<> inline uint32_t Reference::As<uint32_t>() const {
+ return AsUInt32();
+}
+template<> inline uint64_t Reference::As<uint64_t>() const {
+ return AsUInt64();
+}
template<> inline double Reference::As<double>() const { return AsDouble(); }
template<> inline float Reference::As<float>() const { return AsFloat(); }
@@ -1046,7 +1100,7 @@
for (auto key = start; key < stack_.size(); key += 2) {
FLATBUFFERS_ASSERT(stack_[key].type_ == FBT_KEY);
}
- // Now sort values, so later we can do a binary seach lookup.
+ // Now sort values, so later we can do a binary search lookup.
// We want to sort 2 array elements at a time.
struct TwoValue {
Value key;
@@ -1194,6 +1248,24 @@
EndMap(start);
}
+ // If you wish to share a value explicitly (a value not shared automatically
+ // through one of the BUILDER_FLAG_SHARE_* flags) you can do so with these
+ // functions. Or if you wish to turn those flags off for performance reasons
+ // and still do some explicit sharing. For example:
+ // builder.IndirectDouble(M_PI);
+ // auto id = builder.LastValue(); // Remember where we stored it.
+ // .. more code goes here ..
+ // builder.ReuseValue(id); // Refers to same double by offset.
+ // LastValue works regardless of whether the value has a key or not.
+ // Works on any data type.
+ struct Value;
+ Value LastValue() { return stack_.back(); }
+ void ReuseValue(Value v) { stack_.push_back(v); }
+ void ReuseValue(const char *key, Value v) {
+ Key(key);
+ ReuseValue(v);
+ }
+
// Overloaded Add that tries to call the correct function above.
void Add(int8_t i) { Int(i); }
void Add(int16_t i) { Int(i); }
@@ -1319,6 +1391,8 @@
: FBT_INT);
}
+ public:
+ // This was really intended to be private, except for LastValue/ReuseValue.
struct Value {
union {
int64_t i_;
@@ -1343,7 +1417,10 @@
Value(uint64_t u, Type t, BitWidth bw)
: u_(u), type_(t), min_bit_width_(bw) {}
- Value(float f) : f_(f), type_(FBT_FLOAT), min_bit_width_(BIT_WIDTH_32) {}
+ Value(float f)
+ : f_(static_cast<double>(f)),
+ type_(FBT_FLOAT),
+ min_bit_width_(BIT_WIDTH_32) {}
Value(double f) : f_(f), type_(FBT_FLOAT), min_bit_width_(WidthF(f)) {}
uint8_t StoredPackedType(BitWidth parent_bit_width_ = BIT_WIDTH_8) const {
@@ -1388,6 +1465,7 @@
}
};
+ private:
void WriteAny(const Value &val, uint8_t byte_width) {
switch (val.type_) {
case FBT_NULL:
@@ -1420,6 +1498,7 @@
// TODO: instead of asserting, could write vector with larger elements
// instead, though that would be wasteful.
FLATBUFFERS_ASSERT(WidthU(len) <= bit_width);
+ Align(bit_width);
if (!fixed) Write<uint64_t>(len, byte_width);
auto vloc = buf_.size();
for (size_t i = 0; i < len; i++) Write(elems[i], byte_width);
@@ -1431,7 +1510,9 @@
Value CreateVector(size_t start, size_t vec_len, size_t step, bool typed,
bool fixed, const Value *keys = nullptr) {
- FLATBUFFERS_ASSERT(!fixed || typed); // typed=false, fixed=true combination is not supported.
+ FLATBUFFERS_ASSERT(
+ !fixed ||
+ typed); // typed=false, fixed=true combination is not supported.
// Figure out smallest bit width we can store this vector with.
auto bit_width = (std::max)(force_min_bit_width_, WidthU(vec_len));
auto prefix_elems = 1;
@@ -1444,7 +1525,8 @@
Type vector_type = FBT_KEY;
// Check bit widths and types for all elements.
for (size_t i = start; i < stack_.size(); i += step) {
- auto elem_width = stack_[i].ElemWidth(buf_.size(), i + prefix_elems);
+ auto elem_width =
+ stack_[i].ElemWidth(buf_.size(), i - start + prefix_elems);
bit_width = (std::max)(bit_width, elem_width);
if (typed) {
if (i == start) {
@@ -1511,7 +1593,8 @@
typedef std::pair<size_t, size_t> StringOffset;
struct StringOffsetCompare {
- explicit StringOffsetCompare(const std::vector<uint8_t> &buf) : buf_(&buf) {}
+ explicit StringOffsetCompare(const std::vector<uint8_t> &buf)
+ : buf_(&buf) {}
bool operator()(const StringOffset &a, const StringOffset &b) const {
auto stra = reinterpret_cast<const char *>(
flatbuffers::vector_data(*buf_) + a.first);
@@ -1531,8 +1614,8 @@
} // namespace flexbuffers
-# if defined(_MSC_VER)
-# pragma warning(pop)
-# endif
+#if defined(_MSC_VER)
+# pragma warning(pop)
+#endif
#endif // FLATBUFFERS_FLEXBUFFERS_H_
diff --git a/include/flatbuffers/grpc.h b/include/flatbuffers/grpc.h
index a75b67c..bd24c50 100644
--- a/include/flatbuffers/grpc.h
+++ b/include/flatbuffers/grpc.h
@@ -88,8 +88,7 @@
SliceAllocator(const SliceAllocator &other) = delete;
SliceAllocator &operator=(const SliceAllocator &other) = delete;
- SliceAllocator(SliceAllocator &&other)
- : slice_(grpc_empty_slice()) {
+ SliceAllocator(SliceAllocator &&other) : slice_(grpc_empty_slice()) {
// default-construct and swap idiom
swap(other);
}
@@ -164,34 +163,36 @@
public FlatBufferBuilder {
public:
explicit MessageBuilder(uoffset_t initial_size = 1024)
- : FlatBufferBuilder(initial_size, &slice_allocator_, false) {}
+ : FlatBufferBuilder(initial_size, &slice_allocator_, false) {}
MessageBuilder(const MessageBuilder &other) = delete;
MessageBuilder &operator=(const MessageBuilder &other) = delete;
MessageBuilder(MessageBuilder &&other)
- : FlatBufferBuilder(1024, &slice_allocator_, false) {
+ : FlatBufferBuilder(1024, &slice_allocator_, false) {
// Default construct and swap idiom.
Swap(other);
}
/// Create a MessageBuilder from a FlatBufferBuilder.
- explicit MessageBuilder(FlatBufferBuilder &&src, void (*dealloc)(void*, size_t) = &DefaultAllocator::dealloc)
- : FlatBufferBuilder(1024, &slice_allocator_, false) {
+ explicit MessageBuilder(FlatBufferBuilder &&src,
+ void (*dealloc)(void *,
+ size_t) = &DefaultAllocator::dealloc)
+ : FlatBufferBuilder(1024, &slice_allocator_, false) {
src.Swap(*this);
src.SwapBufAllocator(*this);
if (buf_.capacity()) {
- uint8_t *buf = buf_.scratch_data(); // pointer to memory
- size_t capacity = buf_.capacity(); // size of memory
+ uint8_t *buf = buf_.scratch_data(); // pointer to memory
+ size_t capacity = buf_.capacity(); // size of memory
slice_allocator_.slice_ = grpc_slice_new_with_len(buf, capacity, dealloc);
- }
- else {
+ } else {
slice_allocator_.slice_ = grpc_empty_slice();
}
}
/// Move-assign a FlatBufferBuilder to a MessageBuilder.
- /// Only FlatBufferBuilder with default allocator (basically, nullptr) is supported.
+ /// Only FlatBufferBuilder with default allocator (basically, nullptr) is
+ /// supported.
MessageBuilder &operator=(FlatBufferBuilder &&src) {
// Move construct a temporary and swap
MessageBuilder temp(std::move(src));
@@ -209,10 +210,11 @@
void Swap(MessageBuilder &other) {
slice_allocator_.swap(other.slice_allocator_);
FlatBufferBuilder::Swap(other);
- // After swapping the FlatBufferBuilder, we swap back the allocator, which restores
- // the original allocator back in place. This is necessary because MessageBuilder's
- // allocator is its own member (SliceAllocatorMember). The allocator passed to
- // FlatBufferBuilder::vector_downward must point to this member.
+ // After swapping the FlatBufferBuilder, we swap back the allocator, which
+ // restores the original allocator back in place. This is necessary because
+ // MessageBuilder's allocator is its own member (SliceAllocatorMember). The
+ // allocator passed to FlatBufferBuilder::vector_downward must point to this
+ // member.
buf_.swap_allocator(other.buf_);
}
@@ -232,10 +234,10 @@
// flatbuffers-encoded region and wraps it in a `Message<T>` to handle buffer
// ownership.
template<class T> Message<T> GetMessage() {
- auto buf_data = buf_.scratch_data(); // pointer to memory
- auto buf_size = buf_.capacity(); // size of memory
- auto msg_data = buf_.data(); // pointer to msg
- auto msg_size = buf_.size(); // size of msg
+ auto buf_data = buf_.scratch_data(); // pointer to memory
+ auto buf_size = buf_.capacity(); // size of memory
+ auto msg_data = buf_.data(); // pointer to msg
+ auto msg_size = buf_.size(); // size of msg
// Do some sanity checks on data/size
FLATBUFFERS_ASSERT(msg_data);
FLATBUFFERS_ASSERT(msg_size);
@@ -274,7 +276,7 @@
grpc_byte_buffer **buffer, bool *own_buffer) {
// We are passed in a `Message<T>`, which is a wrapper around a
// `grpc_slice`. We extract it here using `BorrowSlice()`. The const cast
- // is necesary because the `grpc_raw_byte_buffer_create` func expects
+ // is necessary because the `grpc_raw_byte_buffer_create` func expects
// non-const slices in order to increment their refcounts.
grpc_slice *slice = const_cast<grpc_slice *>(&msg.BorrowSlice());
// Now use `grpc_raw_byte_buffer_create` to package the single slice into a
@@ -306,7 +308,7 @@
grpc_byte_buffer_reader_init(&reader, buffer);
grpc_slice slice = grpc_byte_buffer_reader_readall(&reader);
grpc_byte_buffer_reader_destroy(&reader);
- // We wrap a `Message<T>` around the slice, but dont increment refcount
+ // We wrap a `Message<T>` around the slice, but don't increment refcount
*msg = flatbuffers::grpc::Message<T>(slice, false);
}
grpc_byte_buffer_destroy(buffer);
diff --git a/include/flatbuffers/hash.h b/include/flatbuffers/hash.h
index 16536cb..aebf071 100644
--- a/include/flatbuffers/hash.h
+++ b/include/flatbuffers/hash.h
@@ -57,17 +57,17 @@
return hash;
}
-template <> inline uint16_t HashFnv1<uint16_t>(const char *input) {
+template<> inline uint16_t HashFnv1<uint16_t>(const char *input) {
uint32_t hash = HashFnv1<uint32_t>(input);
return (hash >> 16) ^ (hash & 0xffff);
}
-template <> inline uint16_t HashFnv1a<uint16_t>(const char *input) {
+template<> inline uint16_t HashFnv1a<uint16_t>(const char *input) {
uint32_t hash = HashFnv1a<uint32_t>(input);
return (hash >> 16) ^ (hash & 0xffff);
}
-template <typename T> struct NamedHashFunction {
+template<typename T> struct NamedHashFunction {
const char *name;
typedef T (*HashFunction)(const char *);
@@ -75,7 +75,7 @@
};
const NamedHashFunction<uint16_t> kHashFunctions16[] = {
- { "fnv1_16", HashFnv1<uint16_t> },
+ { "fnv1_16", HashFnv1<uint16_t> },
{ "fnv1a_16", HashFnv1a<uint16_t> },
};
diff --git a/include/flatbuffers/idl.h b/include/flatbuffers/idl.h
index 44e3566..a28745f 100644
--- a/include/flatbuffers/idl.h
+++ b/include/flatbuffers/idl.h
@@ -47,26 +47,26 @@
// of type tokens.
// clang-format off
#define FLATBUFFERS_GEN_TYPES_SCALAR(TD) \
- TD(NONE, "", uint8_t, byte, byte, byte, uint8, u8, UByte) \
- TD(UTYPE, "", uint8_t, byte, byte, byte, uint8, u8, UByte) /* begin scalar/int */ \
- TD(BOOL, "bool", uint8_t, boolean,bool, bool, bool, bool, Boolean) \
- TD(CHAR, "byte", int8_t, byte, int8, sbyte, int8, i8, Byte) \
- TD(UCHAR, "ubyte", uint8_t, byte, byte, byte, uint8, u8, UByte) \
- TD(SHORT, "short", int16_t, short, int16, short, int16, i16, Short) \
- TD(USHORT, "ushort", uint16_t, short, uint16, ushort, uint16, u16, UShort) \
- TD(INT, "int", int32_t, int, int32, int, int32, i32, Int) \
- TD(UINT, "uint", uint32_t, int, uint32, uint, uint32, u32, UInt) \
- TD(LONG, "long", int64_t, long, int64, long, int64, i64, Long) \
- TD(ULONG, "ulong", uint64_t, long, uint64, ulong, uint64, u64, ULong) /* end int */ \
- TD(FLOAT, "float", float, float, float32, float, float32, f32, Float) /* begin float */ \
- TD(DOUBLE, "double", double, double, float64, double, float64, f64, Double) /* end float/scalar */
+ TD(NONE, "", uint8_t, byte, byte, byte, uint8, u8, UByte, UInt8) \
+ TD(UTYPE, "", uint8_t, byte, byte, byte, uint8, u8, UByte, UInt8) /* begin scalar/int */ \
+ TD(BOOL, "bool", uint8_t, boolean,bool, bool, bool, bool, Boolean, Bool) \
+ TD(CHAR, "byte", int8_t, byte, int8, sbyte, int8, i8, Byte, Int8) \
+ TD(UCHAR, "ubyte", uint8_t, byte, byte, byte, uint8, u8, UByte, UInt8) \
+ TD(SHORT, "short", int16_t, short, int16, short, int16, i16, Short, Int16) \
+ TD(USHORT, "ushort", uint16_t, short, uint16, ushort, uint16, u16, UShort, UInt16) \
+ TD(INT, "int", int32_t, int, int32, int, int32, i32, Int, Int32) \
+ TD(UINT, "uint", uint32_t, int, uint32, uint, uint32, u32, UInt, UInt32) \
+ TD(LONG, "long", int64_t, long, int64, long, int64, i64, Long, Int64) \
+ TD(ULONG, "ulong", uint64_t, long, uint64, ulong, uint64, u64, ULong, UInt64) /* end int */ \
+ TD(FLOAT, "float", float, float, float32, float, float32, f32, Float, Float32) /* begin float */ \
+ TD(DOUBLE, "double", double, double, float64, double, float64, f64, Double, Double) /* end float/scalar */
#define FLATBUFFERS_GEN_TYPES_POINTER(TD) \
- TD(STRING, "string", Offset<void>, int, int, StringOffset, int, unused, Int) \
- TD(VECTOR, "", Offset<void>, int, int, VectorOffset, int, unused, Int) \
- TD(STRUCT, "", Offset<void>, int, int, int, int, unused, Int) \
- TD(UNION, "", Offset<void>, int, int, int, int, unused, Int)
+ TD(STRING, "string", Offset<void>, int, int, StringOffset, int, unused, Int, Offset<String>) \
+ TD(VECTOR, "", Offset<void>, int, int, VectorOffset, int, unused, Int, Offset<UOffset>) \
+ TD(STRUCT, "", Offset<void>, int, int, int, int, unused, Int, Offset<UOffset>) \
+ TD(UNION, "", Offset<void>, int, int, int, int, unused, Int, Offset<UOffset>)
#define FLATBUFFERS_GEN_TYPE_ARRAY(TD) \
- TD(ARRAY, "", int, int, int, int, int, unused, Int)
+ TD(ARRAY, "", int, int, int, int, int, unused, Int, Offset<UOffset>)
// The fields are:
// - enum
// - FlatBuffers schema type.
@@ -91,6 +91,20 @@
}
*/
+// If not all FLATBUFFERS_GEN_() arguments are necessary for implementation
+// of FLATBUFFERS_TD, you can use a variadic macro (with __VA_ARGS__ if needed).
+// In the above example, only CTYPE is used to generate the code, it can be rewritten:
+
+/*
+switch (type) {
+ #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \
+ case BASE_TYPE_ ## ENUM: \
+ // do something specific to CTYPE here
+ FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
+ #undef FLATBUFFERS_TD
+}
+*/
+
#define FLATBUFFERS_GEN_TYPES(TD) \
FLATBUFFERS_GEN_TYPES_SCALAR(TD) \
FLATBUFFERS_GEN_TYPES_POINTER(TD) \
@@ -101,17 +115,15 @@
__extension__ // Stop GCC complaining about trailing comma with -Wpendantic.
#endif
enum BaseType {
- #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, \
- RTYPE, KTYPE) \
- BASE_TYPE_ ## ENUM,
+ #define FLATBUFFERS_TD(ENUM, ...) \
+ BASE_TYPE_ ## ENUM,
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
};
-#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, \
- RTYPE, KTYPE) \
- static_assert(sizeof(CTYPE) <= sizeof(largest_scalar_t), \
- "define largest_scalar_t as " #CTYPE);
+#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \
+ static_assert(sizeof(CTYPE) <= sizeof(largest_scalar_t), \
+ "define largest_scalar_t as " #CTYPE);
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
@@ -227,7 +239,7 @@
struct Namespace {
Namespace() : from_table(0) {}
- // Given a (potentally unqualified) name, return the "fully qualified" name
+ // Given a (potentially unqualified) name, return the "fully qualified" name
// which has a full namespaced descriptor.
// With max_components you can request less than the number of components
// the current namespace has.
@@ -284,6 +296,7 @@
shared(false),
native_inline(false),
flexbuffer(false),
+ optional(false),
nested_flatbuffer(NULL),
padding(0) {}
@@ -292,6 +305,10 @@
bool Deserialize(Parser &parser, const reflection::Field *field);
+ bool IsScalarOptional() const {
+ return IsScalar(value.type.base_type) && optional;
+ }
+
Value value;
bool deprecated; // Field is allowed to be present in old data, but can't be.
// written in new data nor accessed in new code.
@@ -302,6 +319,8 @@
bool native_inline; // Field will be defined inline (instead of as a pointer)
// for native tables if field is a struct.
bool flexbuffer; // This field contains FlexBuffer data.
+ bool optional; // If True, this field is Null (as opposed to default
+ // valued).
StructDef *nested_flatbuffer; // This field contains nested FlatBuffer data.
size_t padding; // Bytes to always pad after this field.
};
@@ -338,45 +357,12 @@
flatbuffers::unique_ptr<std::string> original_location;
};
-inline bool IsStruct(const Type &type) {
- return type.base_type == BASE_TYPE_STRUCT && type.struct_def->fixed;
-}
-
-inline bool IsVector(const Type &type) {
- return type.base_type == BASE_TYPE_VECTOR;
-}
-
-inline bool IsArray(const Type &type) {
- return type.base_type == BASE_TYPE_ARRAY;
-}
-
-inline bool IsSeries(const Type &type) {
- return IsVector(type) || IsArray(type);
-}
-
-inline bool IsEnum(const Type &type) {
- return type.enum_def != nullptr && IsInteger(type.base_type);
-}
-
-inline size_t InlineSize(const Type &type) {
- return IsStruct(type)
- ? type.struct_def->bytesize
- : (IsArray(type)
- ? InlineSize(type.VectorType()) * type.fixed_length
- : SizeOf(type.base_type));
-}
-
-inline size_t InlineAlignment(const Type &type) {
- return IsStruct(type)
- ? type.struct_def->minalign
- : (SizeOf(IsArray(type) ? type.element : type.base_type));
-}
-
struct EnumDef;
struct EnumValBuilder;
struct EnumVal {
- Offset<reflection::EnumVal> Serialize(FlatBufferBuilder *builder, const Parser &parser) const;
+ Offset<reflection::EnumVal> Serialize(FlatBufferBuilder *builder,
+ const Parser &parser) const;
bool Deserialize(const Parser &parser, const reflection::EnumVal *val);
@@ -431,10 +417,7 @@
size_t size() const { return vals.vec.size(); }
- const std::vector<EnumVal *> &Vals() const {
- FLATBUFFERS_ASSERT(false == vals.vec.empty());
- return vals.vec;
- }
+ const std::vector<EnumVal *> &Vals() const { return vals.vec; }
const EnumVal *Lookup(const std::string &enum_name) const {
return vals.Lookup(enum_name);
@@ -455,6 +438,52 @@
SymbolTable<EnumVal> vals;
};
+inline bool IsString(const Type &type) {
+ return type.base_type == BASE_TYPE_STRING;
+}
+
+inline bool IsStruct(const Type &type) {
+ return type.base_type == BASE_TYPE_STRUCT && type.struct_def->fixed;
+}
+
+inline bool IsUnion(const Type &type) {
+ return type.enum_def != nullptr && type.enum_def->is_union;
+}
+
+inline bool IsVector(const Type &type) {
+ return type.base_type == BASE_TYPE_VECTOR;
+}
+
+inline bool IsArray(const Type &type) {
+ return type.base_type == BASE_TYPE_ARRAY;
+}
+
+inline bool IsSeries(const Type &type) {
+ return IsVector(type) || IsArray(type);
+}
+
+inline bool IsEnum(const Type &type) {
+ return type.enum_def != nullptr && IsInteger(type.base_type);
+}
+
+inline size_t InlineSize(const Type &type) {
+ return IsStruct(type)
+ ? type.struct_def->bytesize
+ : (IsArray(type)
+ ? InlineSize(type.VectorType()) * type.fixed_length
+ : SizeOf(type.base_type));
+}
+
+inline size_t InlineAlignment(const Type &type) {
+ if (IsStruct(type)) {
+ return type.struct_def->minalign;
+ } else if (IsArray(type)) {
+ return IsStruct(type.VectorType()) ? type.struct_def->minalign
+ : SizeOf(type.element);
+ } else {
+ return SizeOf(type.base_type);
+ }
+}
inline bool operator==(const EnumVal &lhs, const EnumVal &rhs) {
return lhs.value == rhs.value;
}
@@ -470,7 +499,8 @@
}
struct RPCCall : public Definition {
- Offset<reflection::RPCCall> Serialize(FlatBufferBuilder *builder, const Parser &parser) const;
+ Offset<reflection::RPCCall> Serialize(FlatBufferBuilder *builder,
+ const Parser &parser) const;
bool Deserialize(Parser &parser, const reflection::RPCCall *call);
@@ -478,7 +508,8 @@
};
struct ServiceDef : public Definition {
- Offset<reflection::Service> Serialize(FlatBufferBuilder *builder, const Parser &parser) const;
+ Offset<reflection::Service> Serialize(FlatBufferBuilder *builder,
+ const Parser &parser) const;
bool Deserialize(Parser &parser, const reflection::Service *service);
SymbolTable<RPCCall> calls;
@@ -486,6 +517,9 @@
// Container of options that may apply to any of the source/text generators.
struct IDLOptions {
+ bool gen_jvmstatic;
+ // Use flexbuffers instead for binary and text generation
+ bool use_flexbuffers;
bool strict_json;
bool skip_js_exports;
bool use_goog_js_export_format;
@@ -508,7 +542,9 @@
std::string cpp_object_api_pointer_type;
std::string cpp_object_api_string_type;
bool cpp_object_api_string_flexible_constructor;
+ bool cpp_direct_copy;
bool gen_nullable;
+ bool java_checkerframework;
bool gen_generated;
std::string object_prefix;
std::string object_suffix;
@@ -519,6 +555,7 @@
bool keep_include_path;
bool binary_schema_comments;
bool binary_schema_builtins;
+ bool binary_schema_gen_embed;
bool skip_flatbuffers_import;
std::string go_import;
std::string go_namespace;
@@ -528,7 +565,13 @@
bool size_prefixed;
std::string root_type;
bool force_defaults;
+ bool java_primitive_has_method;
+ bool cs_gen_json_serializer;
std::vector<std::string> cpp_includes;
+ std::string cpp_std;
+ std::string proto_namespace_suffix;
+ std::string filename_suffix;
+ std::string filename_extension;
// Possible options for the more general generator below.
enum Language {
@@ -548,6 +591,7 @@
kLobster = 1 << 13,
kRust = 1 << 14,
kKotlin = 1 << 15,
+ kSwift = 1 << 16,
kMAX
};
@@ -561,12 +605,18 @@
// for code generation.
unsigned long lang_to_generate;
- // If set (default behavior), empty string and vector fields will be set to
- // nullptr to make the flatbuffer more compact.
- bool set_empty_to_null;
+ // If set (default behavior), empty string fields will be set to nullptr to
+ // make the flatbuffer more compact.
+ bool set_empty_strings_to_null;
+
+ // If set (default behavior), empty vector fields will be set to nullptr to
+ // make the flatbuffer more compact.
+ bool set_empty_vectors_to_null;
IDLOptions()
- : strict_json(false),
+ : gen_jvmstatic(false),
+ use_flexbuffers(false),
+ strict_json(false),
skip_js_exports(false),
use_goog_js_export_format(false),
use_ES6_js_export_format(false),
@@ -587,7 +637,9 @@
gen_compare(false),
cpp_object_api_pointer_type("std::unique_ptr"),
cpp_object_api_string_flexible_constructor(false),
+ cpp_direct_copy(true),
gen_nullable(false),
+ java_checkerframework(false),
gen_generated(false),
object_suffix("T"),
union_value_namespacing(true),
@@ -596,16 +648,22 @@
keep_include_path(false),
binary_schema_comments(false),
binary_schema_builtins(false),
+ binary_schema_gen_embed(false),
skip_flatbuffers_import(false),
reexport_ts_modules(true),
js_ts_short_names(false),
protobuf_ascii_alike(false),
size_prefixed(false),
force_defaults(false),
+ java_primitive_has_method(false),
+ cs_gen_json_serializer(false),
+ filename_suffix("_generated"),
+ filename_extension(),
lang(IDLOptions::kJava),
mini_reflect(IDLOptions::kNone),
lang_to_generate(0),
- set_empty_to_null(true) {}
+ set_empty_strings_to_null(true),
+ set_empty_vectors_to_null(true) {}
};
// This encapsulates where the parser is in the current source file.
@@ -698,15 +756,14 @@
explicit Parser(const IDLOptions &options = IDLOptions())
: current_namespace_(nullptr),
empty_namespace_(nullptr),
+ flex_builder_(256, flexbuffers::BUILDER_FLAG_SHARE_ALL),
root_struct_def_(nullptr),
opts(options),
uses_flexbuffers_(false),
source_(nullptr),
anonymous_counter(0),
recurse_protection_counter(0) {
- if (opts.force_defaults) {
- builder_.ForceDefaults(true);
- }
+ if (opts.force_defaults) { builder_.ForceDefaults(true); }
// Start out with the empty namespace being current.
empty_namespace_ = new Namespace();
namespaces_.push_back(empty_namespace_);
@@ -777,9 +834,9 @@
// Fills internal structure as if the schema passed had been loaded by parsing
// with Parse except that included filenames will not be populated.
- bool Deserialize(const reflection::Schema* schema);
+ bool Deserialize(const reflection::Schema *schema);
- Type* DeserializeType(const reflection::Type* type);
+ Type *DeserializeType(const reflection::Type *type);
// Checks that the schema represented by this parser is a safe evolution
// of the schema provided. Returns non-empty error on any problems.
@@ -796,6 +853,11 @@
FLATBUFFERS_CHECKED_ERROR Error(const std::string &msg);
+ // @brief Verify that any of 'opts.lang_to_generate' supports Optional scalars
+ // in a schema.
+ // @param opts Options used to parce a schema and generate code.
+ static bool SupportsOptionalScalars(const flatbuffers::IDLOptions &opts);
+
private:
void Message(const std::string &msg);
void Warning(const std::string &msg);
@@ -815,7 +877,7 @@
const std::string &name, const Type &type,
FieldDef **dest);
FLATBUFFERS_CHECKED_ERROR ParseField(StructDef &struct_def);
- FLATBUFFERS_CHECKED_ERROR ParseString(Value &val);
+ FLATBUFFERS_CHECKED_ERROR ParseString(Value &val, bool use_string_pooling);
FLATBUFFERS_CHECKED_ERROR ParseComma();
FLATBUFFERS_CHECKED_ERROR ParseAnyValue(Value &val, FieldDef *field,
size_t parent_fieldn,
@@ -836,16 +898,20 @@
FLATBUFFERS_CHECKED_ERROR ParseVector(const Type &type, uoffset_t *ovalue,
FieldDef *field, size_t fieldn);
FLATBUFFERS_CHECKED_ERROR ParseArray(Value &array);
- FLATBUFFERS_CHECKED_ERROR ParseNestedFlatbuffer(Value &val, FieldDef *field,
- size_t fieldn,
- const StructDef *parent_struct_def);
+ FLATBUFFERS_CHECKED_ERROR ParseNestedFlatbuffer(
+ Value &val, FieldDef *field, size_t fieldn,
+ const StructDef *parent_struct_def);
FLATBUFFERS_CHECKED_ERROR ParseMetaData(SymbolTable<Value> *attributes);
- FLATBUFFERS_CHECKED_ERROR TryTypedValue(const std::string *name, int dtoken, bool check, Value &e,
- BaseType req, bool *destmatch);
- FLATBUFFERS_CHECKED_ERROR ParseHash(Value &e, FieldDef* field);
+ FLATBUFFERS_CHECKED_ERROR TryTypedValue(const std::string *name, int dtoken,
+ bool check, Value &e, BaseType req,
+ bool *destmatch);
+ FLATBUFFERS_CHECKED_ERROR ParseHash(Value &e, FieldDef *field);
FLATBUFFERS_CHECKED_ERROR TokenError();
- FLATBUFFERS_CHECKED_ERROR ParseSingleValue(const std::string *name, Value &e, bool check_now);
- FLATBUFFERS_CHECKED_ERROR ParseEnumFromString(const Type &type, std::string *result);
+ FLATBUFFERS_CHECKED_ERROR ParseSingleValue(const std::string *name, Value &e,
+ bool check_now);
+ FLATBUFFERS_CHECKED_ERROR ParseFunction(const std::string *name, Value &e);
+ FLATBUFFERS_CHECKED_ERROR ParseEnumFromString(const Type &type,
+ std::string *result);
StructDef *LookupCreateStruct(const std::string &name,
bool create_if_new = true,
bool definition = false);
@@ -853,8 +919,7 @@
FLATBUFFERS_CHECKED_ERROR ParseNamespace();
FLATBUFFERS_CHECKED_ERROR StartStruct(const std::string &name,
StructDef **dest);
- FLATBUFFERS_CHECKED_ERROR StartEnum(const std::string &name,
- bool is_union,
+ FLATBUFFERS_CHECKED_ERROR StartEnum(const std::string &name, bool is_union,
EnumDef **dest);
FLATBUFFERS_CHECKED_ERROR ParseDecl();
FLATBUFFERS_CHECKED_ERROR ParseService();
@@ -870,19 +935,19 @@
FLATBUFFERS_CHECKED_ERROR StartParseFile(const char *source,
const char *source_filename);
FLATBUFFERS_CHECKED_ERROR ParseRoot(const char *_source,
- const char **include_paths,
- const char *source_filename);
+ const char **include_paths,
+ const char *source_filename);
FLATBUFFERS_CHECKED_ERROR DoParse(const char *_source,
- const char **include_paths,
- const char *source_filename,
- const char *include_filename);
- FLATBUFFERS_CHECKED_ERROR CheckClash(std::vector<FieldDef*> &fields,
+ const char **include_paths,
+ const char *source_filename,
+ const char *include_filename);
+ FLATBUFFERS_CHECKED_ERROR CheckClash(std::vector<FieldDef *> &fields,
StructDef *struct_def,
- const char *suffix,
- BaseType baseType);
+ const char *suffix, BaseType baseType);
bool SupportsAdvancedUnionFeatures() const;
bool SupportsAdvancedArrayFeatures() const;
+ bool SupportsOptionalScalars() const;
Namespace *UniqueNamespace(Namespace *ns);
FLATBUFFERS_CHECKED_ERROR RecurseError();
@@ -896,9 +961,11 @@
std::vector<Namespace *> namespaces_;
Namespace *current_namespace_;
Namespace *empty_namespace_;
- std::string error_; // User readable error_ if Parse() == false
+ std::string error_; // User readable error_ if Parse() == false
FlatBufferBuilder builder_; // any data contained in the file
+ flexbuffers::Builder flex_builder_;
+ flexbuffers::Reference flex_root_;
StructDef *root_struct_def_;
std::string file_identifier_;
std::string file_extension_;
@@ -927,6 +994,8 @@
extern std::string MakeCamel(const std::string &in, bool first = true);
+extern std::string MakeScreamingCamel(const std::string &in);
+
// Generate text (JSON) from a given FlatBuffer, and a given Parser
// object that has been populated with the corresponding schema.
// If ident_step is 0, no indentation will be generated. Additionally,
@@ -935,159 +1004,160 @@
// strict_json adds "quotes" around field names if true.
// If the flatbuffer cannot be encoded in JSON (e.g., it contains non-UTF-8
// byte arrays in String values), returns false.
-extern bool GenerateTextFromTable(const Parser &parser,
- const void *table,
+extern bool GenerateTextFromTable(const Parser &parser, const void *table,
const std::string &tablename,
std::string *text);
-extern bool GenerateText(const Parser &parser,
- const void *flatbuffer,
+extern bool GenerateText(const Parser &parser, const void *flatbuffer,
std::string *text);
-extern bool GenerateTextFile(const Parser &parser,
- const std::string &path,
+extern bool GenerateTextFile(const Parser &parser, const std::string &path,
const std::string &file_name);
+// Generate Json schema to string
+// See idl_gen_json_schema.cpp.
+extern bool GenerateJsonSchema(const Parser &parser, std::string *json);
+
// Generate binary files from a given FlatBuffer, and a given Parser
// object that has been populated with the corresponding schema.
-// See idl_gen_general.cpp.
-extern bool GenerateBinary(const Parser &parser,
- const std::string &path,
+// See code_generators.cpp.
+extern bool GenerateBinary(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate a C++ header from the definitions in the Parser object.
// See idl_gen_cpp.
-extern bool GenerateCPP(const Parser &parser,
- const std::string &path,
+extern bool GenerateCPP(const Parser &parser, const std::string &path,
const std::string &file_name);
-extern bool GenerateDart(const Parser &parser,
- const std::string &path,
+// Generate C# files from the definitions in the Parser object.
+// See idl_gen_csharp.cpp.
+extern bool GenerateCSharp(const Parser &parser, const std::string &path,
+ const std::string &file_name);
+
+extern bool GenerateDart(const Parser &parser, const std::string &path,
const std::string &file_name);
-// Generate JavaScript or TypeScript code from the definitions in the Parser object.
-// See idl_gen_js.
-extern bool GenerateJSTS(const Parser &parser,
- const std::string &path,
- const std::string &file_name);
+// Generate Java files from the definitions in the Parser object.
+// See idl_gen_java.cpp.
+extern bool GenerateJava(const Parser &parser, const std::string &path,
+ const std::string &file_name);
+
+// Generate JavaScript or TypeScript code from the definitions in the Parser
+// object. See idl_gen_js.
+extern bool GenerateJSTS(const Parser &parser, const std::string &path,
+ const std::string &file_name);
// Generate Go files from the definitions in the Parser object.
// See idl_gen_go.cpp.
-extern bool GenerateGo(const Parser &parser,
- const std::string &path,
+extern bool GenerateGo(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate Php code from the definitions in the Parser object.
// See idl_gen_php.
-extern bool GeneratePhp(const Parser &parser,
- const std::string &path,
+extern bool GeneratePhp(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate Python files from the definitions in the Parser object.
// See idl_gen_python.cpp.
-extern bool GeneratePython(const Parser &parser,
- const std::string &path,
+extern bool GeneratePython(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate Lobster files from the definitions in the Parser object.
// See idl_gen_lobster.cpp.
-extern bool GenerateLobster(const Parser &parser,
- const std::string &path,
+extern bool GenerateLobster(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate Lua files from the definitions in the Parser object.
// See idl_gen_lua.cpp.
-extern bool GenerateLua(const Parser &parser,
- const std::string &path,
- const std::string &file_name);
+extern bool GenerateLua(const Parser &parser, const std::string &path,
+ const std::string &file_name);
// Generate Rust files from the definitions in the Parser object.
// See idl_gen_rust.cpp.
-extern bool GenerateRust(const Parser &parser,
- const std::string &path,
+extern bool GenerateRust(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate Json schema file
// See idl_gen_json_schema.cpp.
-extern bool GenerateJsonSchema(const Parser &parser,
- const std::string &path,
- const std::string &file_name);
+extern bool GenerateJsonSchema(const Parser &parser, const std::string &path,
+ const std::string &file_name);
extern bool GenerateKotlin(const Parser &parser, const std::string &path,
const std::string &file_name);
-// Generate Java/C#/.. files from the definitions in the Parser object.
-// See idl_gen_general.cpp.
-extern bool GenerateGeneral(const Parser &parser,
- const std::string &path,
- const std::string &file_name);
+// Generate Swift classes.
+// See idl_gen_swift.cpp
+extern bool GenerateSwift(const Parser &parser, const std::string &path,
+ const std::string &file_name);
// Generate a schema file from the internal representation, useful after
// parsing a .proto schema.
extern std::string GenerateFBS(const Parser &parser,
const std::string &file_name);
-extern bool GenerateFBS(const Parser &parser,
- const std::string &path,
+extern bool GenerateFBS(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate a make rule for the generated JavaScript or TypeScript code.
// See idl_gen_js.cpp.
-extern std::string JSTSMakeRule(const Parser &parser,
- const std::string &path,
- const std::string &file_name);
+extern std::string JSTSMakeRule(const Parser &parser, const std::string &path,
+ const std::string &file_name);
// Generate a make rule for the generated C++ header.
// See idl_gen_cpp.cpp.
-extern std::string CPPMakeRule(const Parser &parser,
- const std::string &path,
+extern std::string CPPMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate a make rule for the generated Dart code
// see idl_gen_dart.cpp
-extern std::string DartMakeRule(const Parser &parser,
- const std::string &path,
+extern std::string DartMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate a make rule for the generated Rust code.
// See idl_gen_rust.cpp.
-extern std::string RustMakeRule(const Parser &parser,
- const std::string &path,
+extern std::string RustMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name);
-// Generate a make rule for the generated Java/C#/... files.
-// See idl_gen_general.cpp.
-extern std::string GeneralMakeRule(const Parser &parser,
- const std::string &path,
- const std::string &file_name);
+// Generate a make rule for generated Java or C# files.
+// See code_generators.cpp.
+extern std::string JavaCSharpMakeRule(const Parser &parser,
+ const std::string &path,
+ const std::string &file_name);
// Generate a make rule for the generated text (JSON) files.
// See idl_gen_text.cpp.
-extern std::string TextMakeRule(const Parser &parser,
- const std::string &path,
+extern std::string TextMakeRule(const Parser &parser, const std::string &path,
const std::string &file_names);
// Generate a make rule for the generated binary files.
-// See idl_gen_general.cpp.
-extern std::string BinaryMakeRule(const Parser &parser,
- const std::string &path,
+// See code_generators.cpp.
+extern std::string BinaryMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate GRPC Cpp interfaces.
// See idl_gen_grpc.cpp.
-bool GenerateCppGRPC(const Parser &parser,
- const std::string &path,
+bool GenerateCppGRPC(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate GRPC Go interfaces.
// See idl_gen_grpc.cpp.
-bool GenerateGoGRPC(const Parser &parser,
- const std::string &path,
+bool GenerateGoGRPC(const Parser &parser, const std::string &path,
const std::string &file_name);
// Generate GRPC Java classes.
// See idl_gen_grpc.cpp
-bool GenerateJavaGRPC(const Parser &parser,
- const std::string &path,
+bool GenerateJavaGRPC(const Parser &parser, const std::string &path,
const std::string &file_name);
+// Generate GRPC Python interfaces.
+// See idl_gen_grpc.cpp.
+bool GeneratePythonGRPC(const Parser &parser, const std::string &path,
+ const std::string &file_name);
+
+// Generate GRPC Swift interfaces.
+// See idl_gen_grpc.cpp.
+extern bool GenerateSwiftGRPC(const Parser &parser, const std::string &path,
+ const std::string &file_name);
+
+extern bool GenerateTSGRPC(const Parser &parser, const std::string &path,
+ const std::string &file_name);
} // namespace flatbuffers
#endif // FLATBUFFERS_IDL_H_
diff --git a/include/flatbuffers/minireflect.h b/include/flatbuffers/minireflect.h
index 9d648ec..26fd86c 100644
--- a/include/flatbuffers/minireflect.h
+++ b/include/flatbuffers/minireflect.h
@@ -38,7 +38,7 @@
// These mark the scope of a table or struct.
virtual void StartSequence() {}
virtual void EndSequence() {}
- // Called for each field regardless of wether it is present or not.
+ // Called for each field regardless of whether it is present or not.
// If not present, val == nullptr. set_idx is the index of all set fields.
virtual void Field(size_t /*field_idx*/, size_t /*set_idx*/,
ElementaryType /*type*/, bool /*is_vector*/,
@@ -88,7 +88,8 @@
switch (type_table->st) {
case ST_TABLE:
case ST_UNION: return 4;
- case ST_STRUCT: return static_cast<size_t>(type_table->values[type_table->num_elems]);
+ case ST_STRUCT:
+ return static_cast<size_t>(type_table->values[type_table->num_elems]);
default: FLATBUFFERS_ASSERT(false); return 1;
}
default: FLATBUFFERS_ASSERT(false); return 1;
@@ -233,10 +234,11 @@
visitor->StartSequence();
const uint8_t *prev_val = nullptr;
size_t set_idx = 0;
+ size_t array_idx = 0;
for (size_t i = 0; i < type_table->num_elems; i++) {
auto type_code = type_table->type_codes[i];
auto type = static_cast<ElementaryType>(type_code.base_type);
- auto is_vector = type_code.is_vector != 0;
+ auto is_repeating = type_code.is_repeating != 0;
auto ref_idx = type_code.sequence_ref;
const TypeTable *ref = nullptr;
if (ref_idx >= 0) { ref = type_table->type_refs[ref_idx](); }
@@ -248,15 +250,25 @@
} else {
val = obj + type_table->values[i];
}
- visitor->Field(i, set_idx, type, is_vector, ref, name, val);
+ visitor->Field(i, set_idx, type, is_repeating, ref, name, val);
if (val) {
set_idx++;
- if (is_vector) {
- val += ReadScalar<uoffset_t>(val);
- auto vec = reinterpret_cast<const Vector<uint8_t> *>(val);
+ if (is_repeating) {
+ auto elem_ptr = val;
+ size_t size = 0;
+ if (type_table->st == ST_TABLE) {
+ // variable length vector
+ val += ReadScalar<uoffset_t>(val);
+ auto vec = reinterpret_cast<const Vector<uint8_t> *>(val);
+ elem_ptr = vec->Data();
+ size = vec->size();
+ } else {
+ // otherwise fixed size array
+ size = type_table->array_sizes[array_idx];
+ ++array_idx;
+ }
visitor->StartVector();
- auto elem_ptr = vec->Data();
- for (size_t j = 0; j < vec->size(); j++) {
+ for (size_t j = 0; j < size; j++) {
visitor->Element(j, type, ref, elem_ptr);
IterateValue(type, elem_ptr, ref, prev_val, static_cast<soffset_t>(j),
visitor);
diff --git a/include/flatbuffers/pch/flatc_pch.h b/include/flatbuffers/pch/flatc_pch.h
new file mode 100644
index 0000000..7713279
--- /dev/null
+++ b/include/flatbuffers/pch/flatc_pch.h
@@ -0,0 +1,39 @@
+/*
+ * Copyright 2017 Google Inc. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef FLATBUFFERS_FLATC_PCH_H_
+#define FLATBUFFERS_FLATC_PCH_H_
+
+// stl
+#include <cmath>
+#include <sstream>
+#include <cassert>
+#include <unordered_set>
+#include <unordered_map>
+#include <iostream>
+#include <functional>
+#include <set>
+#include <iterator>
+#include <tuple>
+
+// flatbuffers
+#include "flatbuffers/pch/pch.h"
+#include "flatbuffers/code_generators.h"
+#include "flatbuffers/flatbuffers.h"
+#include "flatbuffers/flexbuffers.h"
+#include "flatbuffers/idl.h"
+
+#endif // FLATBUFFERS_FLATC_PCH_H_
diff --git a/include/flatbuffers/pch/pch.h b/include/flatbuffers/pch/pch.h
new file mode 100644
index 0000000..804e99e
--- /dev/null
+++ b/include/flatbuffers/pch/pch.h
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2017 Google Inc. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef FLATBUFFERS_PCH_H_
+#define FLATBUFFERS_PCH_H_
+
+// stl
+#include <cstdint>
+#include <cstring>
+#include <algorithm>
+#include <list>
+#include <string>
+#include <utility>
+#include <iomanip>
+#include <map>
+#include <memory>
+#include <limits>
+#include <stack>
+#include <vector>
+#include <type_traits>
+
+// flatbuffers
+#include "flatbuffers/util.h"
+
+#endif // FLATBUFFERS_PCH_H_
diff --git a/include/flatbuffers/reflection.h b/include/flatbuffers/reflection.h
index 580ae62..70d9971 100644
--- a/include/flatbuffers/reflection.h
+++ b/include/flatbuffers/reflection.h
@@ -46,7 +46,30 @@
// Size of a basic type, don't use with structs.
inline size_t GetTypeSize(reflection::BaseType base_type) {
// This needs to correspond to the BaseType enum.
- static size_t sizes[] = { 0, 1, 1, 1, 1, 2, 2, 4, 4, 8, 8, 4, 8, 4, 4, 4, 4 };
+ static size_t sizes[] = {
+ 0, // None
+ 1, // UType
+ 1, // Bool
+ 1, // Byte
+ 1, // UByte
+ 2, // Short
+ 2, // UShort
+ 4, // Int
+ 4, // UInt
+ 8, // Long
+ 8, // ULong
+ 4, // Float
+ 8, // Double
+ 4, // String
+ 4, // Vector
+ 4, // Obj
+ 4, // Union
+ 0, // Array. Only used in structs. 0 was chosen to prevent out-of-bounds errors.
+
+ 0 // MaxBaseType. This must be kept the last entry in this array.
+ };
+ static_assert(sizeof(sizes) / sizeof(size_t) == reflection::MaxBaseType + 1,
+ "Size of sizes[] array does not match the count of BaseType enum values.");
return sizes[base_type];
}
@@ -228,7 +251,7 @@
template<typename T>
T *GetAnyVectorElemPointer(const VectorOfAny *vec, size_t i) {
auto elem_ptr = vec->Data() + sizeof(uoffset_t) * i;
- return reinterpret_cast<T*>(elem_ptr + ReadScalar<uoffset_t>(elem_ptr));
+ return reinterpret_cast<T *>(elem_ptr + ReadScalar<uoffset_t>(elem_ptr));
}
// Get the inline-address of a vector element. Useful for Structs (pass Struct
@@ -362,7 +385,6 @@
reinterpret_cast<uint8_t *>(flatbuffers::vector_data(vec_)) + offset_);
}
T *operator->() const { return operator*(); }
- void operator=(const pointer_inside_vector &piv);
private:
size_t offset_;
@@ -470,7 +492,8 @@
// buf should point to the start of flatbuffer data.
// length specifies the size of the flatbuffer data.
bool Verify(const reflection::Schema &schema, const reflection::Object &root,
- const uint8_t *buf, size_t length);
+ const uint8_t *buf, size_t length, uoffset_t max_depth = 64,
+ uoffset_t max_tables = 1000000);
} // namespace flatbuffers
diff --git a/include/flatbuffers/reflection_generated.h b/include/flatbuffers/reflection_generated.h
index 0e73a0f..b98afd6 100644
--- a/include/flatbuffers/reflection_generated.h
+++ b/include/flatbuffers/reflection_generated.h
@@ -9,22 +9,31 @@
namespace reflection {
struct Type;
+struct TypeBuilder;
struct KeyValue;
+struct KeyValueBuilder;
struct EnumVal;
+struct EnumValBuilder;
struct Enum;
+struct EnumBuilder;
struct Field;
+struct FieldBuilder;
struct Object;
+struct ObjectBuilder;
struct RPCCall;
+struct RPCCallBuilder;
struct Service;
+struct ServiceBuilder;
struct Schema;
+struct SchemaBuilder;
enum BaseType {
None = 0,
@@ -44,10 +53,11 @@
Vector = 14,
Obj = 15,
Union = 16,
- Array = 17
+ Array = 17,
+ MaxBaseType = 18
};
-inline const BaseType (&EnumValuesBaseType())[18] {
+inline const BaseType (&EnumValuesBaseType())[19] {
static const BaseType values[] = {
None,
UType,
@@ -66,13 +76,14 @@
Vector,
Obj,
Union,
- Array
+ Array,
+ MaxBaseType
};
return values;
}
inline const char * const *EnumNamesBaseType() {
- static const char * const names[19] = {
+ static const char * const names[20] = {
"None",
"UType",
"Bool",
@@ -91,18 +102,20 @@
"Obj",
"Union",
"Array",
+ "MaxBaseType",
nullptr
};
return names;
}
inline const char *EnumNameBaseType(BaseType e) {
- if (e < None || e > Array) return "";
+ if (flatbuffers::IsOutRange(e, None, MaxBaseType)) return "";
const size_t index = static_cast<size_t>(e);
return EnumNamesBaseType()[index];
}
struct Type FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
+ typedef TypeBuilder Builder;
enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
VT_BASE_TYPE = 4,
VT_ELEMENT = 6,
@@ -132,6 +145,7 @@
};
struct TypeBuilder {
+ typedef Type Table;
flatbuffers::FlatBufferBuilder &fbb_;
flatbuffers::uoffset_t start_;
void add_base_type(reflection::BaseType base_type) {
@@ -150,7 +164,6 @@
: fbb_(_fbb) {
start_ = fbb_.StartTable();
}
- TypeBuilder &operator=(const TypeBuilder &);
flatbuffers::Offset<Type> Finish() {
const auto end = fbb_.EndTable(start_);
auto o = flatbuffers::Offset<Type>(end);
@@ -173,6 +186,7 @@
}
struct KeyValue FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
+ typedef KeyValueBuilder Builder;
enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
VT_KEY = 4,
VT_VALUE = 6
@@ -200,6 +214,7 @@
};
struct KeyValueBuilder {
+ typedef KeyValue Table;
flatbuffers::FlatBufferBuilder &fbb_;
flatbuffers::uoffset_t start_;
void add_key(flatbuffers::Offset<flatbuffers::String> key) {
@@ -212,7 +227,6 @@
: fbb_(_fbb) {
start_ = fbb_.StartTable();
}
- KeyValueBuilder &operator=(const KeyValueBuilder &);
flatbuffers::Offset<KeyValue> Finish() {
const auto end = fbb_.EndTable(start_);
auto o = flatbuffers::Offset<KeyValue>(end);
@@ -244,6 +258,7 @@
}
struct EnumVal FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
+ typedef EnumValBuilder Builder;
enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
VT_NAME = 4,
VT_VALUE = 6,
@@ -289,6 +304,7 @@
};
struct EnumValBuilder {
+ typedef EnumVal Table;
flatbuffers::FlatBufferBuilder &fbb_;
flatbuffers::uoffset_t start_;
void add_name(flatbuffers::Offset<flatbuffers::String> name) {
@@ -310,7 +326,6 @@
: fbb_(_fbb) {
start_ = fbb_.StartTable();
}
- EnumValBuilder &operator=(const EnumValBuilder &);
flatbuffers::Offset<EnumVal> Finish() {
const auto end = fbb_.EndTable(start_);
auto o = flatbuffers::Offset<EnumVal>(end);
@@ -354,6 +369,7 @@
}
struct Enum FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
+ typedef EnumBuilder Builder;
enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
VT_NAME = 4,
VT_VALUES = 6,
@@ -407,6 +423,7 @@
};
struct EnumBuilder {
+ typedef Enum Table;
flatbuffers::FlatBufferBuilder &fbb_;
flatbuffers::uoffset_t start_;
void add_name(flatbuffers::Offset<flatbuffers::String> name) {
@@ -431,7 +448,6 @@
: fbb_(_fbb) {
start_ = fbb_.StartTable();
}
- EnumBuilder &operator=(const EnumBuilder &);
flatbuffers::Offset<Enum> Finish() {
const auto end = fbb_.EndTable(start_);
auto o = flatbuffers::Offset<Enum>(end);
@@ -463,14 +479,14 @@
inline flatbuffers::Offset<Enum> CreateEnumDirect(
flatbuffers::FlatBufferBuilder &_fbb,
const char *name = nullptr,
- const std::vector<flatbuffers::Offset<reflection::EnumVal>> *values = nullptr,
+ std::vector<flatbuffers::Offset<reflection::EnumVal>> *values = nullptr,
bool is_union = false,
flatbuffers::Offset<reflection::Type> underlying_type = 0,
- const std::vector<flatbuffers::Offset<reflection::KeyValue>> *attributes = nullptr,
+ std::vector<flatbuffers::Offset<reflection::KeyValue>> *attributes = nullptr,
const std::vector<flatbuffers::Offset<flatbuffers::String>> *documentation = nullptr) {
auto name__ = name ? _fbb.CreateString(name) : 0;
- auto values__ = values ? _fbb.CreateVector<flatbuffers::Offset<reflection::EnumVal>>(*values) : 0;
- auto attributes__ = attributes ? _fbb.CreateVector<flatbuffers::Offset<reflection::KeyValue>>(*attributes) : 0;
+ auto values__ = values ? _fbb.CreateVectorOfSortedTables<reflection::EnumVal>(values) : 0;
+ auto attributes__ = attributes ? _fbb.CreateVectorOfSortedTables<reflection::KeyValue>(attributes) : 0;
auto documentation__ = documentation ? _fbb.CreateVector<flatbuffers::Offset<flatbuffers::String>>(*documentation) : 0;
return reflection::CreateEnum(
_fbb,
@@ -483,6 +499,7 @@
}
struct Field FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
+ typedef FieldBuilder Builder;
enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
VT_NAME = 4,
VT_TYPE = 6,
@@ -494,7 +511,8 @@
VT_REQUIRED = 18,
VT_KEY = 20,
VT_ATTRIBUTES = 22,
- VT_DOCUMENTATION = 24
+ VT_DOCUMENTATION = 24,
+ VT_OPTIONAL = 26
};
const flatbuffers::String *name() const {
return GetPointer<const flatbuffers::String *>(VT_NAME);
@@ -535,6 +553,9 @@
const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>> *documentation() const {
return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>> *>(VT_DOCUMENTATION);
}
+ bool optional() const {
+ return GetField<uint8_t>(VT_OPTIONAL, 0) != 0;
+ }
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyOffsetRequired(verifier, VT_NAME) &&
@@ -554,11 +575,13 @@
VerifyOffset(verifier, VT_DOCUMENTATION) &&
verifier.VerifyVector(documentation()) &&
verifier.VerifyVectorOfStrings(documentation()) &&
+ VerifyField<uint8_t>(verifier, VT_OPTIONAL) &&
verifier.EndTable();
}
};
struct FieldBuilder {
+ typedef Field Table;
flatbuffers::FlatBufferBuilder &fbb_;
flatbuffers::uoffset_t start_;
void add_name(flatbuffers::Offset<flatbuffers::String> name) {
@@ -594,11 +617,13 @@
void add_documentation(flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>> documentation) {
fbb_.AddOffset(Field::VT_DOCUMENTATION, documentation);
}
+ void add_optional(bool optional) {
+ fbb_.AddElement<uint8_t>(Field::VT_OPTIONAL, static_cast<uint8_t>(optional), 0);
+ }
explicit FieldBuilder(flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
}
- FieldBuilder &operator=(const FieldBuilder &);
flatbuffers::Offset<Field> Finish() {
const auto end = fbb_.EndTable(start_);
auto o = flatbuffers::Offset<Field>(end);
@@ -620,7 +645,8 @@
bool required = false,
bool key = false,
flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<reflection::KeyValue>>> attributes = 0,
- flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>> documentation = 0) {
+ flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>> documentation = 0,
+ bool optional = false) {
FieldBuilder builder_(_fbb);
builder_.add_default_real(default_real);
builder_.add_default_integer(default_integer);
@@ -630,6 +656,7 @@
builder_.add_name(name);
builder_.add_offset(offset);
builder_.add_id(id);
+ builder_.add_optional(optional);
builder_.add_key(key);
builder_.add_required(required);
builder_.add_deprecated(deprecated);
@@ -647,10 +674,11 @@
bool deprecated = false,
bool required = false,
bool key = false,
- const std::vector<flatbuffers::Offset<reflection::KeyValue>> *attributes = nullptr,
- const std::vector<flatbuffers::Offset<flatbuffers::String>> *documentation = nullptr) {
+ std::vector<flatbuffers::Offset<reflection::KeyValue>> *attributes = nullptr,
+ const std::vector<flatbuffers::Offset<flatbuffers::String>> *documentation = nullptr,
+ bool optional = false) {
auto name__ = name ? _fbb.CreateString(name) : 0;
- auto attributes__ = attributes ? _fbb.CreateVector<flatbuffers::Offset<reflection::KeyValue>>(*attributes) : 0;
+ auto attributes__ = attributes ? _fbb.CreateVectorOfSortedTables<reflection::KeyValue>(attributes) : 0;
auto documentation__ = documentation ? _fbb.CreateVector<flatbuffers::Offset<flatbuffers::String>>(*documentation) : 0;
return reflection::CreateField(
_fbb,
@@ -664,10 +692,12 @@
required,
key,
attributes__,
- documentation__);
+ documentation__,
+ optional);
}
struct Object FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
+ typedef ObjectBuilder Builder;
enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
VT_NAME = 4,
VT_FIELDS = 6,
@@ -725,6 +755,7 @@
};
struct ObjectBuilder {
+ typedef Object Table;
flatbuffers::FlatBufferBuilder &fbb_;
flatbuffers::uoffset_t start_;
void add_name(flatbuffers::Offset<flatbuffers::String> name) {
@@ -752,7 +783,6 @@
: fbb_(_fbb) {
start_ = fbb_.StartTable();
}
- ObjectBuilder &operator=(const ObjectBuilder &);
flatbuffers::Offset<Object> Finish() {
const auto end = fbb_.EndTable(start_);
auto o = flatbuffers::Offset<Object>(end);
@@ -785,15 +815,15 @@
inline flatbuffers::Offset<Object> CreateObjectDirect(
flatbuffers::FlatBufferBuilder &_fbb,
const char *name = nullptr,
- const std::vector<flatbuffers::Offset<reflection::Field>> *fields = nullptr,
+ std::vector<flatbuffers::Offset<reflection::Field>> *fields = nullptr,
bool is_struct = false,
int32_t minalign = 0,
int32_t bytesize = 0,
- const std::vector<flatbuffers::Offset<reflection::KeyValue>> *attributes = nullptr,
+ std::vector<flatbuffers::Offset<reflection::KeyValue>> *attributes = nullptr,
const std::vector<flatbuffers::Offset<flatbuffers::String>> *documentation = nullptr) {
auto name__ = name ? _fbb.CreateString(name) : 0;
- auto fields__ = fields ? _fbb.CreateVector<flatbuffers::Offset<reflection::Field>>(*fields) : 0;
- auto attributes__ = attributes ? _fbb.CreateVector<flatbuffers::Offset<reflection::KeyValue>>(*attributes) : 0;
+ auto fields__ = fields ? _fbb.CreateVectorOfSortedTables<reflection::Field>(fields) : 0;
+ auto attributes__ = attributes ? _fbb.CreateVectorOfSortedTables<reflection::KeyValue>(attributes) : 0;
auto documentation__ = documentation ? _fbb.CreateVector<flatbuffers::Offset<flatbuffers::String>>(*documentation) : 0;
return reflection::CreateObject(
_fbb,
@@ -807,6 +837,7 @@
}
struct RPCCall FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
+ typedef RPCCallBuilder Builder;
enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
VT_NAME = 4,
VT_REQUEST = 6,
@@ -854,6 +885,7 @@
};
struct RPCCallBuilder {
+ typedef RPCCall Table;
flatbuffers::FlatBufferBuilder &fbb_;
flatbuffers::uoffset_t start_;
void add_name(flatbuffers::Offset<flatbuffers::String> name) {
@@ -875,7 +907,6 @@
: fbb_(_fbb) {
start_ = fbb_.StartTable();
}
- RPCCallBuilder &operator=(const RPCCallBuilder &);
flatbuffers::Offset<RPCCall> Finish() {
const auto end = fbb_.EndTable(start_);
auto o = flatbuffers::Offset<RPCCall>(end);
@@ -907,10 +938,10 @@
const char *name = nullptr,
flatbuffers::Offset<reflection::Object> request = 0,
flatbuffers::Offset<reflection::Object> response = 0,
- const std::vector<flatbuffers::Offset<reflection::KeyValue>> *attributes = nullptr,
+ std::vector<flatbuffers::Offset<reflection::KeyValue>> *attributes = nullptr,
const std::vector<flatbuffers::Offset<flatbuffers::String>> *documentation = nullptr) {
auto name__ = name ? _fbb.CreateString(name) : 0;
- auto attributes__ = attributes ? _fbb.CreateVector<flatbuffers::Offset<reflection::KeyValue>>(*attributes) : 0;
+ auto attributes__ = attributes ? _fbb.CreateVectorOfSortedTables<reflection::KeyValue>(attributes) : 0;
auto documentation__ = documentation ? _fbb.CreateVector<flatbuffers::Offset<flatbuffers::String>>(*documentation) : 0;
return reflection::CreateRPCCall(
_fbb,
@@ -922,6 +953,7 @@
}
struct Service FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
+ typedef ServiceBuilder Builder;
enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
VT_NAME = 4,
VT_CALLS = 6,
@@ -964,6 +996,7 @@
};
struct ServiceBuilder {
+ typedef Service Table;
flatbuffers::FlatBufferBuilder &fbb_;
flatbuffers::uoffset_t start_;
void add_name(flatbuffers::Offset<flatbuffers::String> name) {
@@ -982,7 +1015,6 @@
: fbb_(_fbb) {
start_ = fbb_.StartTable();
}
- ServiceBuilder &operator=(const ServiceBuilder &);
flatbuffers::Offset<Service> Finish() {
const auto end = fbb_.EndTable(start_);
auto o = flatbuffers::Offset<Service>(end);
@@ -1008,12 +1040,12 @@
inline flatbuffers::Offset<Service> CreateServiceDirect(
flatbuffers::FlatBufferBuilder &_fbb,
const char *name = nullptr,
- const std::vector<flatbuffers::Offset<reflection::RPCCall>> *calls = nullptr,
- const std::vector<flatbuffers::Offset<reflection::KeyValue>> *attributes = nullptr,
+ std::vector<flatbuffers::Offset<reflection::RPCCall>> *calls = nullptr,
+ std::vector<flatbuffers::Offset<reflection::KeyValue>> *attributes = nullptr,
const std::vector<flatbuffers::Offset<flatbuffers::String>> *documentation = nullptr) {
auto name__ = name ? _fbb.CreateString(name) : 0;
- auto calls__ = calls ? _fbb.CreateVector<flatbuffers::Offset<reflection::RPCCall>>(*calls) : 0;
- auto attributes__ = attributes ? _fbb.CreateVector<flatbuffers::Offset<reflection::KeyValue>>(*attributes) : 0;
+ auto calls__ = calls ? _fbb.CreateVectorOfSortedTables<reflection::RPCCall>(calls) : 0;
+ auto attributes__ = attributes ? _fbb.CreateVectorOfSortedTables<reflection::KeyValue>(attributes) : 0;
auto documentation__ = documentation ? _fbb.CreateVector<flatbuffers::Offset<flatbuffers::String>>(*documentation) : 0;
return reflection::CreateService(
_fbb,
@@ -1024,6 +1056,7 @@
}
struct Schema FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
+ typedef SchemaBuilder Builder;
enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE {
VT_OBJECTS = 4,
VT_ENUMS = 6,
@@ -1072,6 +1105,7 @@
};
struct SchemaBuilder {
+ typedef Schema Table;
flatbuffers::FlatBufferBuilder &fbb_;
flatbuffers::uoffset_t start_;
void add_objects(flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<reflection::Object>>> objects) {
@@ -1096,7 +1130,6 @@
: fbb_(_fbb) {
start_ = fbb_.StartTable();
}
- SchemaBuilder &operator=(const SchemaBuilder &);
flatbuffers::Offset<Schema> Finish() {
const auto end = fbb_.EndTable(start_);
auto o = flatbuffers::Offset<Schema>(end);
@@ -1126,17 +1159,17 @@
inline flatbuffers::Offset<Schema> CreateSchemaDirect(
flatbuffers::FlatBufferBuilder &_fbb,
- const std::vector<flatbuffers::Offset<reflection::Object>> *objects = nullptr,
- const std::vector<flatbuffers::Offset<reflection::Enum>> *enums = nullptr,
+ std::vector<flatbuffers::Offset<reflection::Object>> *objects = nullptr,
+ std::vector<flatbuffers::Offset<reflection::Enum>> *enums = nullptr,
const char *file_ident = nullptr,
const char *file_ext = nullptr,
flatbuffers::Offset<reflection::Object> root_table = 0,
- const std::vector<flatbuffers::Offset<reflection::Service>> *services = nullptr) {
- auto objects__ = objects ? _fbb.CreateVector<flatbuffers::Offset<reflection::Object>>(*objects) : 0;
- auto enums__ = enums ? _fbb.CreateVector<flatbuffers::Offset<reflection::Enum>>(*enums) : 0;
+ std::vector<flatbuffers::Offset<reflection::Service>> *services = nullptr) {
+ auto objects__ = objects ? _fbb.CreateVectorOfSortedTables<reflection::Object>(objects) : 0;
+ auto enums__ = enums ? _fbb.CreateVectorOfSortedTables<reflection::Enum>(enums) : 0;
auto file_ident__ = file_ident ? _fbb.CreateString(file_ident) : 0;
auto file_ext__ = file_ext ? _fbb.CreateString(file_ext) : 0;
- auto services__ = services ? _fbb.CreateVector<flatbuffers::Offset<reflection::Service>>(*services) : 0;
+ auto services__ = services ? _fbb.CreateVectorOfSortedTables<reflection::Service>(services) : 0;
return reflection::CreateSchema(
_fbb,
objects__,
diff --git a/include/flatbuffers/stl_emulation.h b/include/flatbuffers/stl_emulation.h
index 6f6e766..66bd620 100644
--- a/include/flatbuffers/stl_emulation.h
+++ b/include/flatbuffers/stl_emulation.h
@@ -18,6 +18,7 @@
#define FLATBUFFERS_STL_EMULATION_H_
// clang-format off
+#include "flatbuffers/base.h"
#include <string>
#include <type_traits>
@@ -33,15 +34,34 @@
#include <cctype>
#endif // defined(FLATBUFFERS_CPP98_STL)
-// Check if we can use template aliases
-// Not possible if Microsoft Compiler before 2012
-// Possible is the language feature __cpp_alias_templates is defined well
-// Or possible if the C++ std is C+11 or newer
-#if (defined(_MSC_VER) && _MSC_VER > 1700 /* MSVC2012 */) \
- || (defined(__cpp_alias_templates) && __cpp_alias_templates >= 200704) \
- || (defined(__cplusplus) && __cplusplus >= 201103L)
- #define FLATBUFFERS_TEMPLATES_ALIASES
-#endif
+// Detect C++17 compatible compiler.
+// __cplusplus >= 201703L - a compiler has support of 'static inline' variables.
+#if defined(FLATBUFFERS_USE_STD_OPTIONAL) \
+ || (defined(__cplusplus) && __cplusplus >= 201703L) \
+ || (defined(_MSVC_LANG) && (_MSVC_LANG >= 201703L))
+ #include <optional>
+ #ifndef FLATBUFFERS_USE_STD_OPTIONAL
+ #define FLATBUFFERS_USE_STD_OPTIONAL
+ #endif
+#endif // defined(FLATBUFFERS_USE_STD_OPTIONAL) ...
+
+// The __cpp_lib_span is the predefined feature macro.
+#if defined(FLATBUFFERS_USE_STD_SPAN)
+ #include <span>
+#elif defined(__cpp_lib_span) && defined(__has_include)
+ #if __has_include(<span>)
+ #include <span>
+ #define FLATBUFFERS_USE_STD_SPAN
+ #endif
+#else
+ // Disable non-trivial ctors if FLATBUFFERS_SPAN_MINIMAL defined.
+ #if !defined(FLATBUFFERS_TEMPLATES_ALIASES) || defined(FLATBUFFERS_CPP98_STL)
+ #define FLATBUFFERS_SPAN_MINIMAL
+ #else
+ // Enable implicit construction of a span<T,N> from a std::array<T,N>.
+ #include <array>
+ #endif
+#endif // defined(FLATBUFFERS_USE_STD_SPAN)
// This header provides backwards compatibility for C++98 STLs like stlport.
namespace flatbuffers {
@@ -96,13 +116,13 @@
}
};
- template <> class numeric_limits<float> :
+ template <> class numeric_limits<float> :
public std::numeric_limits<float> {
public:
static float lowest() { return -FLT_MAX; }
};
- template <> class numeric_limits<double> :
+ template <> class numeric_limits<double> :
public std::numeric_limits<double> {
public:
static double lowest() { return -DBL_MAX; }
@@ -138,7 +158,12 @@
template <typename T, typename U> using is_same = std::is_same<T,U>;
template <typename T> using is_floating_point = std::is_floating_point<T>;
template <typename T> using is_unsigned = std::is_unsigned<T>;
+ template <typename T> using is_enum = std::is_enum<T>;
template <typename T> using make_unsigned = std::make_unsigned<T>;
+ template<bool B, class T, class F>
+ using conditional = std::conditional<B, T, F>;
+ template<class T, T v>
+ using integral_constant = std::integral_constant<T, v>;
#else
// Map C++ TR1 templates defined by stlport.
template <typename T> using is_scalar = std::tr1::is_scalar<T>;
@@ -146,6 +171,7 @@
template <typename T> using is_floating_point =
std::tr1::is_floating_point<T>;
template <typename T> using is_unsigned = std::tr1::is_unsigned<T>;
+ template <typename T> using is_enum = std::tr1::is_enum<T>;
// Android NDK doesn't have std::make_unsigned or std::tr1::make_unsigned.
template<typename T> struct make_unsigned {
static_assert(is_unsigned<T>::value, "Specialization not implemented!");
@@ -157,6 +183,10 @@
template<> struct make_unsigned<long> { using type = unsigned long; };
template<>
struct make_unsigned<long long> { using type = unsigned long long; };
+ template<bool B, class T, class F>
+ using conditional = std::tr1::conditional<B, T, F>;
+ template<class T, T v>
+ using integral_constant = std::tr1::integral_constant<T, v>;
#endif // !FLATBUFFERS_CPP98_STL
#else
// MSVC 2010 doesn't support C++11 aliases.
@@ -165,7 +195,12 @@
template <typename T> struct is_floating_point :
public std::is_floating_point<T> {};
template <typename T> struct is_unsigned : public std::is_unsigned<T> {};
+ template <typename T> struct is_enum : public std::is_enum<T> {};
template <typename T> struct make_unsigned : public std::make_unsigned<T> {};
+ template<bool B, class T, class F>
+ struct conditional : public std::conditional<B, T, F> {};
+ template<class T, T v>
+ struct integral_constant : public std::integral_constant<T, v> {};
#endif // defined(FLATBUFFERS_TEMPLATES_ALIASES)
#ifndef FLATBUFFERS_CPP98_STL
@@ -175,7 +210,7 @@
// MSVC 2010 doesn't support C++11 aliases.
// We're manually "aliasing" the class here as we want to bring unique_ptr
// into the flatbuffers namespace. We have unique_ptr in the flatbuffers
- // namespace we have a completely independent implemenation (see below)
+ // namespace we have a completely independent implementation (see below)
// for C++98 STL implementations.
template <class T> class unique_ptr : public std::unique_ptr<T> {
public:
@@ -268,8 +303,365 @@
template <class T> bool operator==(const unique_ptr<T>& x, intptr_t y) {
return reinterpret_cast<intptr_t>(x.get()) == y;
}
+
+ template <class T> bool operator!=(const unique_ptr<T>& x, decltype(nullptr)) {
+ return !!x;
+ }
+
+ template <class T> bool operator!=(decltype(nullptr), const unique_ptr<T>& x) {
+ return !!x;
+ }
+
+ template <class T> bool operator==(const unique_ptr<T>& x, decltype(nullptr)) {
+ return !x;
+ }
+
+ template <class T> bool operator==(decltype(nullptr), const unique_ptr<T>& x) {
+ return !x;
+ }
+
#endif // !FLATBUFFERS_CPP98_STL
+#ifdef FLATBUFFERS_USE_STD_OPTIONAL
+template<class T>
+using Optional = std::optional<T>;
+using nullopt_t = std::nullopt_t;
+inline constexpr nullopt_t nullopt = std::nullopt;
+
+#else
+// Limited implementation of Optional<T> type for a scalar T.
+// This implementation limited by trivial types compatible with
+// std::is_arithmetic<T> or std::is_enum<T> type traits.
+
+// A tag to indicate an empty flatbuffers::optional<T>.
+struct nullopt_t {
+ explicit FLATBUFFERS_CONSTEXPR_CPP11 nullopt_t(int) {}
+};
+
+#if defined(FLATBUFFERS_CONSTEXPR_DEFINED)
+ namespace internal {
+ template <class> struct nullopt_holder {
+ static constexpr nullopt_t instance_ = nullopt_t(0);
+ };
+ template<class Dummy>
+ constexpr nullopt_t nullopt_holder<Dummy>::instance_;
+ }
+ static constexpr const nullopt_t &nullopt = internal::nullopt_holder<void>::instance_;
+
+#else
+ namespace internal {
+ template <class> struct nullopt_holder {
+ static const nullopt_t instance_;
+ };
+ template<class Dummy>
+ const nullopt_t nullopt_holder<Dummy>::instance_ = nullopt_t(0);
+ }
+ static const nullopt_t &nullopt = internal::nullopt_holder<void>::instance_;
+
+#endif
+
+template<class T>
+class Optional FLATBUFFERS_FINAL_CLASS {
+ // Non-scalar 'T' would extremely complicated Optional<T>.
+ // Use is_scalar<T> checking because flatbuffers flatbuffers::is_arithmetic<T>
+ // isn't implemented.
+ static_assert(flatbuffers::is_scalar<T>::value, "unexpected type T");
+
+ public:
+ ~Optional() {}
+
+ FLATBUFFERS_CONSTEXPR_CPP11 Optional() FLATBUFFERS_NOEXCEPT
+ : value_(), has_value_(false) {}
+
+ FLATBUFFERS_CONSTEXPR_CPP11 Optional(nullopt_t) FLATBUFFERS_NOEXCEPT
+ : value_(), has_value_(false) {}
+
+ FLATBUFFERS_CONSTEXPR_CPP11 Optional(T val) FLATBUFFERS_NOEXCEPT
+ : value_(val), has_value_(true) {}
+
+ FLATBUFFERS_CONSTEXPR_CPP11 Optional(const Optional &other) FLATBUFFERS_NOEXCEPT
+ : value_(other.value_), has_value_(other.has_value_) {}
+
+ FLATBUFFERS_CONSTEXPR_CPP14 Optional &operator=(const Optional &other) FLATBUFFERS_NOEXCEPT {
+ value_ = other.value_;
+ has_value_ = other.has_value_;
+ return *this;
+ }
+
+ FLATBUFFERS_CONSTEXPR_CPP14 Optional &operator=(nullopt_t) FLATBUFFERS_NOEXCEPT {
+ value_ = T();
+ has_value_ = false;
+ return *this;
+ }
+
+ FLATBUFFERS_CONSTEXPR_CPP14 Optional &operator=(T val) FLATBUFFERS_NOEXCEPT {
+ value_ = val;
+ has_value_ = true;
+ return *this;
+ }
+
+ void reset() FLATBUFFERS_NOEXCEPT {
+ *this = nullopt;
+ }
+
+ void swap(Optional &other) FLATBUFFERS_NOEXCEPT {
+ std::swap(value_, other.value_);
+ std::swap(has_value_, other.has_value_);
+ }
+
+ FLATBUFFERS_CONSTEXPR_CPP11 FLATBUFFERS_EXPLICIT_CPP11 operator bool() const FLATBUFFERS_NOEXCEPT {
+ return has_value_;
+ }
+
+ FLATBUFFERS_CONSTEXPR_CPP11 bool has_value() const FLATBUFFERS_NOEXCEPT {
+ return has_value_;
+ }
+
+ FLATBUFFERS_CONSTEXPR_CPP11 const T& operator*() const FLATBUFFERS_NOEXCEPT {
+ return value_;
+ }
+
+ const T& value() const {
+ FLATBUFFERS_ASSERT(has_value());
+ return value_;
+ }
+
+ T value_or(T default_value) const FLATBUFFERS_NOEXCEPT {
+ return has_value() ? value_ : default_value;
+ }
+
+ private:
+ T value_;
+ bool has_value_;
+};
+
+template<class T>
+FLATBUFFERS_CONSTEXPR_CPP11 bool operator==(const Optional<T>& opt, nullopt_t) FLATBUFFERS_NOEXCEPT {
+ return !opt;
+}
+template<class T>
+FLATBUFFERS_CONSTEXPR_CPP11 bool operator==(nullopt_t, const Optional<T>& opt) FLATBUFFERS_NOEXCEPT {
+ return !opt;
+}
+
+template<class T, class U>
+FLATBUFFERS_CONSTEXPR_CPP11 bool operator==(const Optional<T>& lhs, const U& rhs) FLATBUFFERS_NOEXCEPT {
+ return static_cast<bool>(lhs) && (*lhs == rhs);
+}
+
+template<class T, class U>
+FLATBUFFERS_CONSTEXPR_CPP11 bool operator==(const T& lhs, const Optional<U>& rhs) FLATBUFFERS_NOEXCEPT {
+ return static_cast<bool>(rhs) && (lhs == *rhs);
+}
+
+template<class T, class U>
+FLATBUFFERS_CONSTEXPR_CPP11 bool operator==(const Optional<T>& lhs, const Optional<U>& rhs) FLATBUFFERS_NOEXCEPT {
+ return static_cast<bool>(lhs) != static_cast<bool>(rhs)
+ ? false
+ : !static_cast<bool>(lhs) ? false : (*lhs == *rhs);
+}
+#endif // FLATBUFFERS_USE_STD_OPTIONAL
+
+
+// Very limited and naive partial implementation of C++20 std::span<T,Extent>.
+#if defined(FLATBUFFERS_USE_STD_SPAN)
+ inline constexpr std::size_t dynamic_extent = std::dynamic_extent;
+ template<class T, std::size_t Extent = std::dynamic_extent>
+ using span = std::span<T, Extent>;
+
+#else // !defined(FLATBUFFERS_USE_STD_SPAN)
+FLATBUFFERS_CONSTEXPR std::size_t dynamic_extent = static_cast<std::size_t>(-1);
+
+// Exclude this code if MSVC2010 or non-STL Android is active.
+// The non-STL Android doesn't have `std::is_convertible` required for SFINAE.
+#if !defined(FLATBUFFERS_SPAN_MINIMAL)
+namespace internal {
+ // This is SFINAE helper class for checking of a common condition:
+ // > This overload only participates in overload resolution
+ // > Check whether a pointer to an array of U can be converted
+ // > to a pointer to an array of E.
+ // This helper is used for checking of 'U -> const U'.
+ template<class E, std::size_t Extent, class U, std::size_t N>
+ struct is_span_convertable {
+ using type =
+ typename std::conditional<std::is_convertible<U (*)[], E (*)[]>::value
+ && (Extent == dynamic_extent || N == Extent),
+ int, void>::type;
+ };
+
+} // namespace internal
+#endif // !defined(FLATBUFFERS_SPAN_MINIMAL)
+
+// T - element type; must be a complete type that is not an abstract
+// class type.
+// Extent - the number of elements in the sequence, or dynamic.
+template<class T, std::size_t Extent = dynamic_extent>
+class span FLATBUFFERS_FINAL_CLASS {
+ public:
+ typedef T element_type;
+ typedef T& reference;
+ typedef const T& const_reference;
+ typedef T* pointer;
+ typedef const T* const_pointer;
+ typedef std::size_t size_type;
+
+ static FLATBUFFERS_CONSTEXPR size_type extent = Extent;
+
+ // Returns the number of elements in the span.
+ FLATBUFFERS_CONSTEXPR_CPP11 size_type size() const FLATBUFFERS_NOEXCEPT {
+ return count_;
+ }
+
+ // Returns the size of the sequence in bytes.
+ FLATBUFFERS_CONSTEXPR_CPP11
+ size_type size_bytes() const FLATBUFFERS_NOEXCEPT {
+ return size() * sizeof(element_type);
+ }
+
+ // Checks if the span is empty.
+ FLATBUFFERS_CONSTEXPR_CPP11 bool empty() const FLATBUFFERS_NOEXCEPT {
+ return size() == 0;
+ }
+
+ // Returns a pointer to the beginning of the sequence.
+ FLATBUFFERS_CONSTEXPR_CPP11 pointer data() const FLATBUFFERS_NOEXCEPT {
+ return data_;
+ }
+
+ // Returns a reference to the idx-th element of the sequence.
+ // The behavior is undefined if the idx is greater than or equal to size().
+ FLATBUFFERS_CONSTEXPR_CPP11 reference operator[](size_type idx) const {
+ return data()[idx];
+ }
+
+ FLATBUFFERS_CONSTEXPR_CPP11 span(const span &other) FLATBUFFERS_NOEXCEPT
+ : data_(other.data_), count_(other.count_) {}
+
+ FLATBUFFERS_CONSTEXPR_CPP14 span &operator=(const span &other)
+ FLATBUFFERS_NOEXCEPT {
+ data_ = other.data_;
+ count_ = other.count_;
+ }
+
+ // Limited implementation of
+ // `template <class It> constexpr std::span(It first, size_type count);`.
+ //
+ // Constructs a span that is a view over the range [first, first + count);
+ // the resulting span has: data() == first and size() == count.
+ // The behavior is undefined if [first, first + count) is not a valid range,
+ // or if (extent != flatbuffers::dynamic_extent && count != extent).
+ FLATBUFFERS_CONSTEXPR_CPP11
+ explicit span(pointer first, size_type count) FLATBUFFERS_NOEXCEPT
+ : data_ (Extent == dynamic_extent ? first : (Extent == count ? first : nullptr)),
+ count_(Extent == dynamic_extent ? count : (Extent == count ? Extent : 0)) {
+ // Make span empty if the count argument is incompatible with span<T,N>.
+ }
+
+ // Exclude this code if MSVC2010 is active. The MSVC2010 isn't C++11
+ // compliant, it doesn't support default template arguments for functions.
+ #if defined(FLATBUFFERS_SPAN_MINIMAL)
+ FLATBUFFERS_CONSTEXPR_CPP11 span() FLATBUFFERS_NOEXCEPT : data_(nullptr),
+ count_(0) {
+ static_assert(extent == 0 || extent == dynamic_extent, "invalid span");
+ }
+
+ #else
+ // Constructs an empty span whose data() == nullptr and size() == 0.
+ // This overload only participates in overload resolution if
+ // extent == 0 || extent == flatbuffers::dynamic_extent.
+ // A dummy template argument N is need dependency for SFINAE.
+ template<std::size_t N = 0,
+ typename internal::is_span_convertable<element_type, Extent, element_type, (N - N)>::type = 0>
+ FLATBUFFERS_CONSTEXPR_CPP11 span() FLATBUFFERS_NOEXCEPT : data_(nullptr),
+ count_(0) {
+ static_assert(extent == 0 || extent == dynamic_extent, "invalid span");
+ }
+
+ // Constructs a span that is a view over the array arr; the resulting span
+ // has size() == N and data() == std::data(arr). These overloads only
+ // participate in overload resolution if
+ // extent == std::dynamic_extent || N == extent is true and
+ // std::remove_pointer_t<decltype(std::data(arr))>(*)[]
+ // is convertible to element_type (*)[].
+ template<std::size_t N,
+ typename internal::is_span_convertable<element_type, Extent, element_type, N>::type = 0>
+ FLATBUFFERS_CONSTEXPR_CPP11 span(element_type (&arr)[N]) FLATBUFFERS_NOEXCEPT
+ : data_(arr), count_(N) {}
+
+ template<class U, std::size_t N,
+ typename internal::is_span_convertable<element_type, Extent, U, N>::type = 0>
+ FLATBUFFERS_CONSTEXPR_CPP11 span(std::array<U, N> &arr) FLATBUFFERS_NOEXCEPT
+ : data_(arr.data()), count_(N) {}
+
+ //template<class U, std::size_t N,
+ // int = 0>
+ //FLATBUFFERS_CONSTEXPR_CPP11 span(std::array<U, N> &arr) FLATBUFFERS_NOEXCEPT
+ // : data_(arr.data()), count_(N) {}
+
+ template<class U, std::size_t N,
+ typename internal::is_span_convertable<element_type, Extent, U, N>::type = 0>
+ FLATBUFFERS_CONSTEXPR_CPP11 span(const std::array<U, N> &arr) FLATBUFFERS_NOEXCEPT
+ : data_(arr.data()), count_(N) {}
+
+ // Converting constructor from another span s;
+ // the resulting span has size() == s.size() and data() == s.data().
+ // This overload only participates in overload resolution
+ // if extent == std::dynamic_extent || N == extent is true and U (*)[]
+ // is convertible to element_type (*)[].
+ template<class U, std::size_t N,
+ typename internal::is_span_convertable<element_type, Extent, U, N>::type = 0>
+ FLATBUFFERS_CONSTEXPR_CPP11 span(const flatbuffers::span<U, N> &s) FLATBUFFERS_NOEXCEPT
+ : span(s.data(), s.size()) {
+ }
+
+ #endif // !defined(FLATBUFFERS_SPAN_MINIMAL)
+
+ private:
+ // This is a naive implementation with 'count_' member even if (Extent != dynamic_extent).
+ pointer const data_;
+ const size_type count_;
+};
+
+ #if !defined(FLATBUFFERS_SPAN_MINIMAL)
+ template<class U, std::size_t N>
+ FLATBUFFERS_CONSTEXPR_CPP11
+ flatbuffers::span<U, N> make_span(U(&arr)[N]) FLATBUFFERS_NOEXCEPT {
+ return span<U, N>(arr);
+ }
+
+ template<class U, std::size_t N>
+ FLATBUFFERS_CONSTEXPR_CPP11
+ flatbuffers::span<const U, N> make_span(const U(&arr)[N]) FLATBUFFERS_NOEXCEPT {
+ return span<const U, N>(arr);
+ }
+
+ template<class U, std::size_t N>
+ FLATBUFFERS_CONSTEXPR_CPP11
+ flatbuffers::span<U, N> make_span(std::array<U, N> &arr) FLATBUFFERS_NOEXCEPT {
+ return span<U, N>(arr);
+ }
+
+ template<class U, std::size_t N>
+ FLATBUFFERS_CONSTEXPR_CPP11
+ flatbuffers::span<const U, N> make_span(const std::array<U, N> &arr) FLATBUFFERS_NOEXCEPT {
+ return span<const U, N>(arr);
+ }
+
+ template<class U, std::size_t N>
+ FLATBUFFERS_CONSTEXPR_CPP11
+ flatbuffers::span<U, dynamic_extent> make_span(U *first, std::size_t count) FLATBUFFERS_NOEXCEPT {
+ return span<U, dynamic_extent>(first, count);
+ }
+
+ template<class U, std::size_t N>
+ FLATBUFFERS_CONSTEXPR_CPP11
+ flatbuffers::span<const U, dynamic_extent> make_span(const U *first, std::size_t count) FLATBUFFERS_NOEXCEPT {
+ return span<const U, dynamic_extent>(first, count);
+ }
+#endif
+
+#endif // defined(FLATBUFFERS_USE_STD_SPAN)
+
} // namespace flatbuffers
#endif // FLATBUFFERS_STL_EMULATION_H_
diff --git a/include/flatbuffers/util.h b/include/flatbuffers/util.h
index 072fe9e..2aafa48 100644
--- a/include/flatbuffers/util.h
+++ b/include/flatbuffers/util.h
@@ -17,10 +17,11 @@
#ifndef FLATBUFFERS_UTIL_H_
#define FLATBUFFERS_UTIL_H_
-#include "flatbuffers/base.h"
-
#include <errno.h>
+#include "flatbuffers/base.h"
+#include "flatbuffers/stl_emulation.h"
+
#ifndef FLATBUFFERS_PREFER_PRINTF
# include <sstream>
#else // FLATBUFFERS_PREFER_PRINTF
@@ -72,6 +73,14 @@
// Case-insensitive isalnum
inline bool is_alnum(char c) { return is_alpha(c) || is_digit(c); }
+inline char CharToUpper(char c) {
+ return static_cast<char>(::toupper(static_cast<unsigned char>(c)));
+}
+
+inline char CharToLower(char c) {
+ return static_cast<char>(::tolower(static_cast<unsigned char>(c)));
+}
+
// @end-locale-independent functions for ASCII character set
#ifdef FLATBUFFERS_PREFER_PRINTF
@@ -446,7 +455,7 @@
// Strip the last component of the path + separator.
std::string StripFileName(const std::string &filepath);
-// Concatenates a path with a filename, regardless of wether the path
+// Concatenates a path with a filename, regardless of whether the path
// ends in a separator or not.
std::string ConCatPathFileName(const std::string &path,
const std::string &filename);
@@ -636,6 +645,32 @@
return true;
}
+inline std::string BufferToHexText(const void *buffer, size_t buffer_size,
+ size_t max_length,
+ const std::string &wrapped_line_prefix,
+ const std::string &wrapped_line_suffix) {
+ std::string text = wrapped_line_prefix;
+ size_t start_offset = 0;
+ const char *s = reinterpret_cast<const char *>(buffer);
+ for (size_t i = 0; s && i < buffer_size; i++) {
+ // Last iteration or do we have more?
+ bool have_more = i + 1 < buffer_size;
+ text += "0x";
+ text += IntToStringHex(static_cast<uint8_t>(s[i]), 2);
+ if (have_more) { text += ','; }
+ // If we have more to process and we reached max_length
+ if (have_more &&
+ text.size() + wrapped_line_suffix.size() >= start_offset + max_length) {
+ text += wrapped_line_suffix;
+ text += '\n';
+ start_offset = text.size();
+ text += wrapped_line_prefix;
+ }
+ }
+ text += wrapped_line_suffix;
+ return text;
+}
+
// Remove paired quotes in a string: "text"|'text' -> text.
std::string RemoveStringQuotes(const std::string &s);