Squashed 'third_party/flatbuffers/' changes from 338393f85..e5f331db9
e5f331db9 [TS] Add single-file ts codegen & bazel rule for typescript (#7161)
2f84c6038 Apply Namer to Go code gen (#7150)
d64839651 [Lobster] file_identifier support
777e78d8d [Lobster] support unsigned integer reads
4016c549d Apply Namer to Python code gen (#7146)
40827b21b Fix missing 'break' (#7151)
65a10b6e3 Implement a config based name manager and use it in Rust codegen (#7144)
8db2fef3f [TS] Escape keywords in typescript object names (#7137)
9ed132304 Fix 64-bit numeric enum values in typescript (#7135)
1a4c40566 updated npm to 2.0.6
318594e4b prevent name clash (#7133)
3d903302c [Rust] Add length checks to arrays and vectors. (#7130)
c9571d989 Replaced ToDasherCase with ConvertCase (#7131)
3694b830a Use ConvertCase instead of Make{Upper,Lower,Snake} implementations (#7127)
0471fa807 remove stall reference to version
914344ea9 some minor help edits
b40266c56 Use target_compile_features to target C++11 (#7122)
8a9303d46 update proto tests with alaised enum (#7121)
30c4bf47f Trigger fuzzing CI only on relevant changes (#7120)
46ce45601 remove auto generate code from cmakelists (#7119)
433312c55 add the missing checkNullConditionnal code in the "GenObjApi" function when the field is scalar optional (#7114)
9c52ec374 Add deps attribute to flatbuffer_cc_library (#7107)
70e2f49bf fixed string-json -> strict-json typo
5ac0367ed [TS] Fix generation of reserved words in object api (#7106) (#7115)
5d101afb5 Fix minor typo in WhitePaper.md (#7108)
06f4af11b Go optional scalars (#7104)
57e338f81 explicitly use windows-2019 to unblock ci (#7105)
615616cb5 Change Rust generated file defaults (#7101)
3413c3300 Fixed FlexBuffers verifier fuzzer timing out
69f5660a4 Fixed Parser not checking size of union types vector
d5add9fca Fixed FlexBuffers ToString unquoted non-ident keys
15df50eb7 Remove @ExperimentalUnsignedTypes annotation from kotlin code generator. (#7092)
a94132a45 Swift FlatBufferBuilder.sizedByteArray to ByteBuffer.toArray() (#7093)
48befb6be [TS] Refactor away circular ref (#7099)
b30069133 Add reflection support for python (#7026)
faadbc10e Add CreateVector overload to accept array like (#7095)
ed6ae8d32 explicitly defined std::allocator (#7094)
e910bddbc [JS] Add ".js" suffix to all import statements to generate a browser compatible mjs version. (#7086)
c85fb690f Add Parsing Completed function for Rust (#7084)
c1daa6ba0 rust: Bump thiserror version and remove git dependency (#7080)
4c71c7b02 replace framework include of flatbuffers (#7079)
f5664d33f fix go_test implement error (#7012)
39c8a19ce fixed comparator for native_inline (#7076)
826193ff6 skip generating reflection.fbs in generate_scripts (#7077)
fd0d1ed92 update C++ generator to emit scoped enums in vector of unions (#7075)
424988f30 replaced removed xml tag
b2550dbaa removed BSD-3-Clause license and Zlib licenses (#7073)
a2b238960 Fixed default value of bool in struct for Swift (#7072)
619b78437 one last dart omit local (#7070)
68a766154 more omit type annotations for dart local variables (#7069)
7dac9961f omit type annotations for dart local variables (#7067)
c65c389c6 add xmlns to .Net (#7066)
6446dcf3d Updates swift gen licence for grpc code (#7063)
e090d8da1 Fixed long cast to int in flexbufferbuilder.java (#7059)
bc901436d clang format on codebase (#7058)
240be9b5a attempt to remove appveyor (#7056)
bc366a7f9 Provide a short help text and default in error case (#6992)
14b19d446 Use FindPython3 (#7055)
9e6f17b94 remove BIICODE
c3801ad37 Update readme.md
4f3b24db0 Fixes a bug where bools arent being nil when marked optional (#7051)
1d294a31b Implement Serialize on generated rust types (#7022)
dd8fccfb1 Cmake 3.16 de-facto minimum version (#7049)
7089c9ecd Convert flatbuffers_version_string to inline function (#7046)
43203984f [C++] Support C++ object copies and moves (#5988)
5993338ee [ts] Builder incorrectly serializing empty strings (#7047)
19920db39 Include a SizePrefixed..HasIdentifier for c++. (#6871)
dbbaeac85 Use `${PYTHON_EXECUTABLE}` instead of `py` in cmake (#7042)
028f0fde6 'flattest': Add --test_path option (#7041)
87343631b Added support for clang-cl on windows (CMake) (#7038)
1fbfaf5c5 Fix/cmake build grpc (#7028)
4421375bb Add FlatBuffers::FlatBuffers interface, needed for FetchContent_Declare (#7023)
162ad7a37 Fix comment with line orders - Rust should be last. (#7037)
a0a6c3f8c Use actions/checkout@v2, which fixes security vulnerability. (#7036)
a2d38fbb9 Add --warnings-as-errors to flatc compiler. (#7034)
9ef1524d3 Emit include for bfbs-gen-embed (#7031)
0c9de0352 Upgraded GRPC version to 1.42.0 (#7033)
a783bc926 chore: dart 2.0.5 release changes (#6983)
aff818ceb rust: Allow for usage in no_std environment (#6989)
d7b75417f Make flatbuffer builder deterministic (#6993)
a42e89897 Added verifier alignment checking to table fields (#7018)
96cc2f3ee BuildFlatBuffers.cmake: fix arguments not passed properly to flatc (#7013)
3250a1f8d Add initial C# vector of unions support to the documentation. (#6880)
ace4a37f2 [TS/JS] BigInt implementation (#6998)
f28c2b293 Avoid implicit conversion from float to double. (#7003)
96f3cf690 Rearrange #include directives to pass to compilation with a particular DSP toolchain (#7000)
b3edfdbfb Reverting grpc generated file suffix (#6995)
b8aaccee8 Disable parsing of nested_flatbuffers as bytes by default
2dc8ae774 Enable OSS-Fuzz on CI
5b0d49112 Updated FlexBuffers fuzzer
d8b7041d7 Added alignment checking to FlexBuffers verifier
5a0c3366c FlexBuffers verifier additionally checks for nesting
f8148b8da Made FlexBuffers reuse tracker track types
a22b1b626 Prevent shadow with _{{FIELD_NAME}} (#6991)
4264daadd FlexBuffers fuzzer fixes
3cbc120a0 Refractor Flatc Options (#6987)
8dcd2682c [CMake] Add option for disable universal on OSX (#6990)
b78002ff3 Validate C# json/object-api options (#6985)
c555ee8fa Add .NET test to github workflows (#6982)
b92bb0584 [CMake]: Fix version in pkgconfig file (#6986)
956d11569 re-enabled FlexBuffer JSON in fuzzer
e367ca32a Verifier for FlexBuffers (#6977)
705f27f6e [CMake]: Fix python command for mingw environment (#6984)
5fc87f4c4 Enable --gen-onefile in Python (#6953)
11749095a Make idl_parser deterministic (#6976)
d0cede9c9 Bumping to Version 2.0.5 (#6967)
fcc2bee0b Fix typo in variable name (#6973)
e08da4dea remove Appveyor's Vs2010 and 13 builds (#6969)
18538c401 [TS] Fix reserved words as arguments (#6955) (#6956)
e57f4ab2d Update stale bot version and provide away to exempt issues with the not-stale label (#6968)
deed68db5 missing generated files (#6966)
061d61f3f Lua Generator using IR. (#6940)
cffe0c454 FixedTypedVector: add const to ElementType() and size() (#6965)
fadd40e40 Have grpc include file with correct filename-suffix given to flatc (#6954)
e47dc0e46 Removed test/generate_code.{sh|bat} (#6873)
5c5475479 switched to windows-lastest, removed deadcode (#6948)
4f7f6dc30 Restore FlatBufferBuilder::kFileIdentifierLength. (#6960)
0fadaf391 Enable verifier on nested_flatbuffers
4d0e9a870 Turn off nested FlatBuffers/FlexBuffers for the fuzzer
c05f6783a invalid conditional running genrate_code.py (#6952)
a14f4052c rust: remove needless borrow (#6922)
9e4ca857b Vector Downward GetSize optimization (#6925)
a2b99084b Fix flexbuffers clang-analyzer warning (#6947)
85b4effac test: fix undefined order of functio parameters. (#6946)
790f41154 [cmake] Fix getting version info from tags during the build (#6936)
e89de4411 clang-all (#6941)
256ab3798 WIP: Dart release 2.0 (#6927)
a59288a01 Add benchmarks to Linux CI (#6928)
587bbd49a [C++] Fix compile failure on Object API union construction for struct member (#6923)
a9c341545 Fix integer overflow warnings
8aa18b629 fixed cmp0048 error (#6932)
d727579b6 fuzzers: fix typo in file path (#6931)
97a30171c Added Raw C++ benchmarks (#6924)
0989fc5e5 Added Google benchmarks (and gtests) (#6920)
927175ea2 [Java] lookup by byteArray is giving back wrong entry (#6915)
6748c373b Removal of support for FLATBUFFERS_CPP98_STL (#6918)
3fab0c6ee move [[ ]] to calling sites (#6914)
6c8c29155 [C++] Split flatbuffers.h into separate files (#6868)
fd4ff23da Keep methods with struct name and switch them to default (#6879)
f8b69e330 [Python] Verify EnumDef is not generated in GenUnionCreator (#6903)
c0394bb09 Support `--conform` for vector of unions (#6883)
8433eb108 Typo fixes in comments of flatbuffers.h and flexbuffers.h (#6901)
f2f9380c8 [Java] Prevent generation of enum names when underlying type is long (#6781) (#6895)
e672dabfe [C++] Fix memory leak when using grpc (#6896) (#6897)
9a4ca2764 Output errors / warnings on stderr instead of stdout (#6881)
4c7a9c10d Adds JSON encoding to swift (#6874)
38295a187 [Kotlin] Fix missing escape for struct construction statements (#6877)
31bb0b972 add working directory (#6878)
45e5642e9 Default Arguments for Mutators C++ [Updated] (#6872)
a592f4c89 [Cmake] Add a post build command after flatc to run the new generate_code.py script. (#6866)
b9d43a557 dart - add Packable interface (#6846)
2ece9e25b Bumped package.json to 2.0.4
2dd212637 Fix linker errors on (Free|Open)BSD. (#6860)
f63c130c2 Improves documentation, and adding DocC (#6784)
e2b26ee19 Make and generate_code.sh generate same outputs (#6855)
9d686bf43 Include subdirectories in published npm package (#6850)
1d26daff3 Use ArrayBuffer type for JS flexbuffer's toObject (#6851)
e72e18d9f feat(build): compile "universal" libraries and executables for Mac (#6852)
354d97f6d fixed errant itemgroup element in C# test project (#6854)
6f7a57eaa [C#] Using 'global::' as qualifying_start_ within BaseGenerator (#6767)
90baa1444 Dart: binary lists (typed_data) (#6839)
0a3b017f0 Delete IDLOptions::lang (#6841)
47d35f105 BugFix: Optional enum when it is null (#6835)
8fb8c2ce1 [C#] Use @ for keyword escaping (#6834)
1d063d87c [C++] Let builder accept custom-alloc std::vector (#6814)
338331b55 Changes to support binary schema file loading and parsing (flatc) (#6823)
156a30c75 Move Apple-specific build flags to Clang section (#6802)
550d2f904 Issue error if jsonschema has no root type defined #6821 (#6831)
c3a38242e Fix typos in docs (#6829)
74c3d7eba [C++] Add mutable version of LookupByKey and test (#6826)
db6eae5c4 Add html and latex to gitignore (#6819)
0e9d79c35 [Java] Avoid casting ByteBuffer to Buffer (#6785)
b20c4d3aa [C++] Add GetMutableSizePrefixedRoot and generate GetMutableSizePrefixedXxx functions (#6815)
ae145293c flattests_cpp17 doesn't compile with Visual Studio 2017: warning C4100: 'indent': unreferenced formal parameter (#6811)
e3c76a5cd Dart lints (#6808)
4b9123baf fix parser string=null (#6810)
f89e0b1a6 Refactor idl_gen_rust and Rust generated code to use consistent whitespace (#6809)
273f6084e Fix Rust keyword inconsistency (#6794)
4a0879458 [C#] Remove superfluous semicolon in C# structs (#6791)
d6f51ea16 fix ptr in flatbuffers cpp tutorial (#6787)
067dce6e7 [C#] Handle keywords (#6775)
2ca5f0e72 [C#] Respect command line parameter for file name extension and suffix (#6779)
f20d2253a update Java version to 2.0.3
390d438e2 [Kotlin] Fix CI by changing compiler to Java 11 (#6783)
6fb2c90d9 avoiding even more NoSuchMethod exceptions (#6729)
a7b527d94 java: Use maven profile to target Java 8 bytecode (#6764)
5d77820b3 [C++] Using calculated fields_number for field_names size (#6769)
909ce970a [C++] Use UnPackTo instead of UnPack if pointer exists (#6725)
35e2cac6e Store vtables sorted in Rust builder (#6765)
c39fc9dd9 [C++] Use nullptr instead of 0 in generated headers (#6762)
775c6567d [C++] Fix compiler warning -Wredundant-parens in clang (#6761)
97d9527f6 Dart 2.0 release prep (#6759)
e01205466 [C++] Use proper gRPC C++ API when using MemoryBuffer Slice (#6756)
5235133f3 Dart - make ascii optimization optional in StringReader, same as in writeString() (#6758)
c871df770 Dart - change table building to assert() instead of exceptions (#6754)
a6eeeb3b9 Dart - inline small functions to increase performance (#6755)
3dd02144d [C#] Fix field name struct name collision (#6744) (#6757)
e77926f0e [C#] Add Union Constructor Utility for ObjectAPI. (#6105)
ac2348202 Dart - fixup writeString() return type after previous merges (#6753)
8be8a0a71 [C++] Fix union type handling on object api in C++17 (#6745)
12e341e4f Rework how Rust generated files are laid out (#6731)
c36672d80 Dart - optimize writeString for ASCII (#6736)
2bfc8e9f0 Dart - make writeString() argument non-nullable (#6737)
674a9f2aa fix lints in rust tests (#6743)
016e6aa13 Add a split on ':' to build_defs.bzl (#6742)
65700441d Dart - make vTable fixed size (expect the number of fields when creating) (#6735)
dd5bb55ca Dart - make vTable deduplication optional (#6734)
e8423da1b Dart - regenerate example after recent flatc changes (#6733)
0980e39c9 flexbuffers: Add variant of Blob() that takes a key (#6730)
e73fab27d Dart - store empty vectors instead of NULL (#6728)
92ae532e4 Dart - finish/lowFinish/buffer changes (#6712)
7482b25f8 Remove ubuntu1604 from presubmit.yml (#6715)
3f77dc9a0 Dart - unpack() must use eager list reader (#6723)
838c93b84 Dart - fix flex-builder compilation error (#6722)
089f48a4a Dart - make sure added padding is zeroed, same as in C++ (#6716)
bf3470c16 Fix UB in CreateVectorOfStructs in case of an empty vector: avoid calling memcpy in this case (#6726)
8f8196e13 Fix 6348 (#6717)
8ab35b2a5 Dart - add custom allocator support (#6711)
c0ba2870c Fix typo in docu (#6714)
22498cf3a [C++] add make_span for Array<T,N> (#6663)
bd37e67ac [C++] Fix a -Wdeprecated-copy warning. (#6708)
a6ee33557 Dart null safety (#6696)
71d43f3be Make --bfbs-filenames default to location of first schema file. (#6705)
c8db1ca5d Jsonschema add prop comments (#6617)
962751a6e Improve generated comparisons for tables (#6486)
06fd6d640 Replace filenames in reflection with filenames+includes. (#6703)
acce4ac3f Fix incorrect assertion usage. (#6702)
8fd7861b7 Fix warning about deprecated module: imp (#6362)
c58ae9422 Add the file a symbol is declared in to Reflection (#6613)
2cf7bb796 Intermediate Representation docs (#6685)
4e3a66c14 Dart object API (#6682)
d959e2320 dart - change Builder.reset() to reuse an existing buffer (#6661)
a9fb54088 use improved versioning (#6691)
337eb8b8f update docs - structs can't be roots (#6690)
6415ef05d [Python] [Codegen] Fixes nested structs with underscore names (#6686)
f069396d1 [C++] flatc --cpp-field-case-style option to permit camel-case field names in C++ (#6669)
021177af0 Fix snap version formatting (#6683)
e1e9f9373 [C++/grpc] added hiding of unused variables in the generated code (#6677)
15110094e Fix GitHub Actions CI gcc/clang versions
093badb0a Use unoptimized path for ReadUInt64 for win32 build as the optimized path crashes. (#6681)
752c7b576 avoiding more NoSuchMethod exceptions (#6671)
7c3e267e1 [Java] ObjectAPI implementation (#6521) (#6582)
baaffbaed npm update to 2.0.3 and script fix
4cb3f222b [TS] Fix module reference in package.json (#6676)
eabdbda75 [TS] Generate entry point module (#6674)
bec23700f Prepare for Java 2.0.1 release
12f2eedad Update CI to GCC/Clang 11
221eeb231 Fix typo in C++ doc (#6664)
813d3632e avoiding NoSuchMethod exception (#6658)
d84bccb0c Removed most heap allocations in builder (#6662)
b4e67f9bf Dart test fix (#6660)
54c11932f [Java] Flexbuffers - Negative signed object length (#6651)
fbcb3c423 [TS/JS] Updates the grpc (#6654)
8937dcfd7 Updates go lang support to allow other languages to communicate with it (#6653)
512d5a689 Update readme.md to point to security policy
a92cb5dd7 Create Security.md
d151dcbb9 Revert "[C++] Removed most heap allocations in builder (#6620)" (#6659)
f1884c66f Fix gRPC test to use EndVector without specifying the length. (#6646)
72730ecd8 [C++] Removed most heap allocations in builder (#6620)
fe2bc2b0a Added README for Rust Flatbuffers (before publishing v=2.0) (#6652)
4867c9456 Fixed generation of c++ code with flags (#6637)
ef0eb3701 Ran clang-format-all.sh. Removed default --style=file parameter (#6639)
f83ee1af5 [idl_parser] Check structs and enums do not clash in a namespace (#6562)
a5175c513 Implements verifier and code gen for swift (#6373)
04b10f5a3 Deprecate EnumVal.object (#6612)
c121c0345 Fixed Java gRPC version number dependency
8fd10606c Implement Serialize for flexbuffer::Reader (#6635)
a1730fcea [Swift] Updated cocoapods to 2.0.0 (#6634)
a9a295fec More missing version changes
5c01ad387 Dart generated code update
42ca1b914 Swift/Kotlin generated code version updates
6ed780dbd C++/Rust version changes
3412fab8e C#/Java generated code version updates
8a7d013f8 Updated main version numbers to 2.0
170af5978 [Go] Add missing namespace when using Object API (#6633)
c8c16de16 Fix reverse iterators for Vector and Array (#6626)
4525cd9c5 [Lua] manipulate byte array as string (#6624)
47361baf6 [C++] Fix union copy constructor to work with nested structs (#6552) (#6607)
8a582883a Updates swift generated monster sample file (#6616)
a4bb8f0c2 [Lua] Avoid infinite loop when creating empty string (#6614)
82aed82b8 Added support for Lua 5.1, 5.2 and 5.4 (#6606)
60ff76630 [TS] Remove wrong and obsolete NS prefix use (#6604)
a27c7d809 Fixed LuaJIT when not compiled with COMPAT mode (#6605)
363220823 removed unneeded type prefixing (#6601)
6b44c605b Bump Rust to 0.9.0 (#6610)
d3cd78a87 [Lua] Add LuaJIT support (#6584)
8fa3dfdb5 Introduce new_from_vec in Rust (also fix formatting) (#6599)
29379e8e4 fix typo in CppUsage.md (#6595)
14725d6c3 [Lua] GetRootAs can accept strings. Made Luatest Benchmarks optional (#6593)
16836ff95 Add advance feature indicators to reflection (#6546)
c87179e73 Rust Remove SafeSliceAccess for Arrays, and fix miri. (#6592)
c24031c36 Mark endian_scalar as unsafe. (#6588)
4ccc52c7a [swift] Implements union strings (#6589)
b82fe0738 [Rust] Fix small mistyping (#6585)
1e7f6c8c7 [TS] Commit the generated tests code (#6579)
84714b109 chore: ensure bash is used to generate code (#6577)
1045d7dd4 [Lua] Fix EnforceNumberAndPack for bool type (#6576)
0c7777596 [TS] Remove duplicated build-ts ci (#6575)
c43ba1752 [Rust] Specify Minimum Supported Rust Version (#6573)
da3bb64ef [Rust] Add support for fixed size arrays (#6548)
151900ba9 [Kotlin][FlexBuffers] Add support for Kotlin-iOS (#6564)
c012f29f9 silenced clippy warning (#6565)
df2df21ec [Kotlin] Bump kotlinx.benchmark dependency to 0.3.0 (#6560)
408e4db4a [TS] Add Build TS to CI jobs (#6524)
4d2364f34 [Kotlin][FlexBuffers] Add support for Kotlin-JS (#6554)
261cf3b20 Default-empty vectors of enums (#6505)
cd67261bb [CI] fixes buildkite (#6544)
1aa0c2f6a Limit formatter to pull requests only (#6540)
4133a39df Rust structz (#6539)
1c26d2a1a [Kotlin][FlexBuffers] JSON support for Flexbuffers (#6417)
276b1bc34 [grpc] Support latest version of grpc PoC (#6338)
124654ffc fixed packing structs (#6530)
3b7d1e86b [GO] Tries to add go format to the CI (#6518)
78f0c0d1d [C++] #6501 - Problem when mapping a native type multiple times (#6514)
c992eafb5 [fuzzer] Add `monster_debug` target (#6513)
ef8dd7792 [Swift] Removes allman rule (#6519)
69b329fc8 [flexbuffers, json] Parse `nan` and `inf` (#6512)
6543ba529 fixed packing structs in nested buffers (#6509)
0e453ac35 [idl_parser] Add kTokenNumericConstant token (#6432)
e9b4ae69d Remove `flatbuffers.pc` from the repository (#6508)
fc4fffea4 Bump grpc to 1.0.0 (#6507)
b240ab704 Move Traits struct and Create method out of --cpp-static-reflection. (#6503)
9a4f1f434 Disable x64-specific optimizations for ARM64EC ReadInt64 (#6506)
fac64918d Add --cpp-static-reflection to generate_code.bat. (#6502)
a69815f72 [C++17] Add compile-time reflection for fields. (#6324)
4033ff589 fixed invalid TS call and added test files (#6495)
a08357251 disable clippy (#6494)
5319dedb1 [idl_parser, JSON] Disable parsing of JSON for incomplete schemes (#6493)
bd4e0b30a [idl_parser] Track included files by hash (#6434)
bf9061200 fix for noUncheckedIndexedAccess in ts (#6474)
8142fedd1 Working on a python example plus fixing python grpc code (#6456)
c0be1cb7a [rust] Remove debug code (#6475)
8cccdfba5 Revert "[C#] Fix truncated ArraySegment<byte> if elementSize != 1 (#6462)" (#6488)
cbbbaa61b [C#] Fix truncated ArraySegment<byte> if elementSize != 1 (#6462)
ffc2ef77c [CI] Adds Code Generation tests on Github Actions (#6482)
1da6f4f18 [CMake] generate pkg-config flatbuffers.pc file (#6455)
b5da526e6 [Swift] Moves grpc example to grpc/examples (#6479)
3b5365762 [TS] Moves grpc code to examples folder (#6476)
e2f5438ac Fixes grammer (#6477)
5e3613f73 Fix sample_binary.py to use latest EndVector without a size. (#6478)
e6b911d40 updated JS docs to reflect current status (#6436)
0c7ae5816 [Go] Working on a go example plus fixing go grpc code (#6448)
ae603b977 [Swift] adds support for default vectors and strings (#6461)
7f47718b6 Update Building.md (#6473)
54dc09e8a GetUOffsetT must get value by GetUint32 not GetInt32 (#6072)
334c6be49 Fix a typo in Swift codegen (#6470)
4174c10e7 [rust] Genericize flexbuffer reader (#6450)
a20f606c2 [Swift] Renaming protocols (#6469)
a72a20827 Update swift docs (#6460)
86401e078 Default strings and vectors: Parser + Rust support (#6421)
6af37e672 [CMake] Renames BUILD files (#6457)
1b88655b0 [Build, cmake] Add -Werror override option (#6429)
0b15916e5 [C++]Fix extra char generation for byte type during json schema generation (#6276)
60eed0ca6 Updating working code (#6441)
0f83367f5 JSON schema - tailing double quotes for maximum (#6452)
fee095410 [idl_parser] Validate `force_align` on all possible paths (#6430)
6f3e45eca Implement Rust object API defaults (#6444)
815d3e820 Upgrade swift grpc to alpha 24 (#6439)
76e7a0ff5 [fuzzer] Limit parser_fuzzer execution time (#6431)
6d91096a2 This commit contains the initial implementation of Flexbuffers in Kotlin. The code was ported based (#6387)
13d9e3585 Better python generated code naming (#6336)
6effe431b Rust: remove inner attributes (#6410)
efcbdc769 [Rust] Ensure unions are referenced with the correct path (#6422)
e581013e3 Refactor FieldDef to model presense as an enum rather than 2 bools. (#6420)
0984d4328 [c++] Apply NativeName before WrapInNameSpace in idl_gen_cpp.cpp (#6419)
786f69b24 Formats cpp code (#6349)
1da0a2dfa Rust Object API (#6070)
796ed68fa Clarify that (Flat|Flex)Buffers do not deduplicate vector elements (#6415)
7b1ee31d8 Clarify that FlatBuffers unions do not support scalars (#6416)
4aff1198d Explain how FlatBuffers encodes unions (#6414)
ad3a729f9 dart Builder - expose finished buffer size (#6403)
52e217706 Remove invalid claim that Protocol Buffers does not support unions (#6413)
760c65755 [TS/JS] New gen TS code gen (#6302)
75c859e98 [idl_parser] Improve symbols lookup thru parent namespaces (#6407)
91b0958c4 Search for includes in the directory containg the current file (#6371)
8008dde11 Upgrade Rust dependencies (#6406)
c81cf8249 [TS/JS] New gen TS code gen prequel to preserve history (#6404)
8573108bb Unset FieldDef.optional if its key (#6402)
7abe612b5 [fuzzer] Fix the binary schema loading in the monster_fuzzer (#6396)
408cf5802 Fix Rust UB problems (#6393)
39e115fdb Define Vector::value_type for STL compatibility (#6394)
85719669c [fuzzer] Debug the monster_tets.bfbs on clusterfuzz server (#6392)
809fe49c7 Fix up scripts, fix generated enum value for strong mode, regenerate files (#6389)
41253e574 [go] tests/GoTest.sh: Fix flags.Parse location to work on new go SDKs. (#6388)
08d2ce844 fix Dart Builder._writeString() - always write trailing zero byte (#6390)
a15a8d930 fix Dart Builder.reset() - clear vTables (#6386)
83ce29cc2 [C++, JSON] Fix nullptr access when reading a key with a default value. (#6375)
4363c1d2c Fix generated EndVector. (#6385)
1bf1ec027 Implements type promotion for Java enum (#6382)
080097653 Delete label_notify.yml
795408115 Disabled PHP CI (#6381)
46545e627 fixed warnings (#6355)
0168178a1 Fix multiple fbs code generation failure (#6365)
82836a62b [idl_parser] Improve stack overflow protection (#6364)
e7430bbeb [idl_parser] Check the range of explicitly set field's id value (#6363)
24dd85fd2 Generate code to encode and decode nested flatbuffers in Python. (#6354)
57f68e289 [Rust] Shared String (#6367)
44cf2bde1 Updates license date to 2021 (#6378)
be37d4da1 include_prefix support for rust (#6330)
4e79d129c [Swift] Rebuild the way swift handles structs from scratch (#6326)
05192553f Fix typos in usage/comments; Make rust generator respect to --filenam… (#6342)
f2511d7d4 Renaming infinity variables in test.cpp (#6340)
f8b203c9c Add vectorNumElements attribute to Builder for simpler vector creation. (#6328)
8ab7c7e2c [CI] Adds formatter to CI (#6272)
7e0039028 Fix Max CI build path (#6333)
65c415911 Generate nullable properties in C# object-based API for optional scalars. (without -gen-mutable) (#6273)
a9e91116d [Python] Commit some orphan python genfile diffs. (#6325)
80a745d9b Fixed missing ending quotes in labeller (#6327)
9fca5e4f4 Add flatc option to inhibit all warnings #6005 (#6301)
92a806b4e [fuzzer] Rename fuzzing dictionaries for `oss-fuzz` (#6318)
9c9baf6d5 bumprust (#6322)
aafc5dc95 Set default initialSize for Builder to 0 (#6310)
442949bc1 Rust Flatbuffers Verifier (#6269)
9064072e8 Version message should be a "STATUS" to avoid going to stderr. (#6316)
fd4c1b5ff Replace std::string and const char* CreateSharedString with string_view (#6315)
bc7eb8ade [fuzzer] Fix mistakes in the `parser` and `scalar` fuzzers. (#6314)
fc960f367 Add default to offset param of Python generated GetRootAs (#6312)
f437f0f7e [fuzzer] Fix loading of schema in monster_fuzzer (#6308)
7f33cf682 [C++] Switch `flatc` to `--cpp-std c++11` C++ code generator (#6306)
8d9eae9ac [idl_parser] Unify parsing of NaN values read from .fbs and .json files (#6296)
2046bffa4 Moved various language tests from AppVeyor to GitHub Actions (#6300)
git-subtree-dir: third_party/flatbuffers
git-subtree-split: e5f331db998a808f78cf5a4880e6f5d0a321c4d0
Signed-off-by: James Kuszmaul <jabukuszmaul+collab@gmail.com>
Change-Id: I37f8aaf007fc86226cfa250169a87807afa64a78
diff --git a/dart/lib/flat_buffers.dart b/dart/lib/flat_buffers.dart
index 3d4cf81..d27d4bf 100644
--- a/dart/lib/flat_buffers.dart
+++ b/dart/lib/flat_buffers.dart
@@ -22,69 +22,70 @@
///
/// This callback is used by other struct's `finish` methods to write the nested
/// struct's fields inline.
-typedef void StructBuilder();
+typedef StructBuilder = void Function();
/// Buffer with data and some context about it.
class BufferContext {
final ByteData _buffer;
- factory BufferContext.fromBytes(List<int> byteList) {
- Uint8List uint8List = _asUint8List(byteList);
- ByteData buf = new ByteData.view(uint8List.buffer, uint8List.offsetInBytes);
- return new BufferContext._(buf);
- }
+ ByteData get buffer => _buffer;
- BufferContext._(this._buffer);
+ /// Create from a FlatBuffer represented by a list of bytes (uint8).
+ factory BufferContext.fromBytes(List<int> byteList) =>
+ BufferContext(byteList is Uint8List
+ ? byteList.buffer.asByteData(byteList.offsetInBytes)
+ : ByteData.view(Uint8List.fromList(byteList).buffer));
- int derefObject(int offset) {
- return offset + _getUint32(offset);
- }
+ /// Create from a FlatBuffer represented by ByteData.
+ BufferContext(this._buffer);
- Uint8List _asUint8LIst(int offset, int length) =>
+ @pragma('vm:prefer-inline')
+ int derefObject(int offset) => offset + _getUint32(offset);
+
+ @pragma('vm:prefer-inline')
+ Uint8List _asUint8List(int offset, int length) =>
_buffer.buffer.asUint8List(_buffer.offsetInBytes + offset, length);
- double _getFloat64(int offset) =>
- _buffer.getFloat64(offset, Endian.little);
+ @pragma('vm:prefer-inline')
+ double _getFloat64(int offset) => _buffer.getFloat64(offset, Endian.little);
- double _getFloat32(int offset) =>
- _buffer.getFloat32(offset, Endian.little);
+ @pragma('vm:prefer-inline')
+ double _getFloat32(int offset) => _buffer.getFloat32(offset, Endian.little);
- int _getInt64(int offset) =>
- _buffer.getInt64(offset, Endian.little);
+ @pragma('vm:prefer-inline')
+ int _getInt64(int offset) => _buffer.getInt64(offset, Endian.little);
- int _getInt32(int offset) =>
- _buffer.getInt32(offset, Endian.little);
+ @pragma('vm:prefer-inline')
+ int _getInt32(int offset) => _buffer.getInt32(offset, Endian.little);
- int _getInt16(int offset) =>
- _buffer.getInt16(offset, Endian.little);
+ @pragma('vm:prefer-inline')
+ int _getInt16(int offset) => _buffer.getInt16(offset, Endian.little);
+ @pragma('vm:prefer-inline')
int _getInt8(int offset) => _buffer.getInt8(offset);
- int _getUint64(int offset) =>
- _buffer.getUint64(offset, Endian.little);
+ @pragma('vm:prefer-inline')
+ int _getUint64(int offset) => _buffer.getUint64(offset, Endian.little);
- int _getUint32(int offset) =>
- _buffer.getUint32(offset, Endian.little);
+ @pragma('vm:prefer-inline')
+ int _getUint32(int offset) => _buffer.getUint32(offset, Endian.little);
- int _getUint16(int offset) =>
- _buffer.getUint16(offset, Endian.little);
+ @pragma('vm:prefer-inline')
+ int _getUint16(int offset) => _buffer.getUint16(offset, Endian.little);
+ @pragma('vm:prefer-inline')
int _getUint8(int offset) => _buffer.getUint8(offset);
+}
- /// If the [byteList] is already a [Uint8List] return it.
- /// Otherwise return a [Uint8List] copy of the [byteList].
- static Uint8List _asUint8List(List<int> byteList) {
- if (byteList is Uint8List) {
- return byteList;
- } else {
- return new Uint8List.fromList(byteList);
- }
- }
+/// Interface implemented by the "object-api" classes (ending with "T").
+abstract class Packable {
+ /// Serialize the object using the given builder, returning the offset.
+ int pack(Builder fbBuilder);
}
/// Class implemented by typed builders generated by flatc.
abstract class ObjectBuilder {
- int _firstOffset;
+ int? _firstOffset;
/// Can be used to write the data represented by this builder to the [Builder]
/// and reuse the offset created in multiple tables.
@@ -94,7 +95,7 @@
/// first call to this method.
int getOrCreateOffset(Builder fbBuilder) {
_firstOffset ??= finish(fbBuilder);
- return _firstOffset;
+ return _firstOffset!;
}
/// Writes the data in this helper to the [Builder].
@@ -107,34 +108,39 @@
/// Class that helps building flat buffers.
class Builder {
+ bool _finished = false;
+
final int initialSize;
/// The list of existing VTable(s).
- //final List<_VTable> _vTables = <_VTable>[];
- final List<int> _vTables = <int>[];
+ final List<int> _vTables;
+
+ final bool deduplicateTables;
ByteData _buf;
+ final Allocator _allocator;
+
/// The maximum alignment that has been seen so far. If [_buf] has to be
/// reallocated in the future (to insert room at its start for more bytes) the
/// reallocation will need to be a multiple of this many bytes.
- int _maxAlign;
+ int _maxAlign = 1;
/// The number of bytes that have been written to the buffer so far. The
/// most recently written byte is this many bytes from the end of [_buf].
- int _tail;
+ int _tail = 0;
/// The location of the end of the current table, measured in bytes from the
- /// end of [_buf], or `null` if a table is not currently being built.
- int _currentTableEndTail;
+ /// end of [_buf].
+ int _currentTableEndTail = 0;
- _VTable _currentVTable;
+ _VTable? _currentVTable;
/// Map containing all strings that have been written so far. This allows us
/// to avoid duplicating strings.
///
/// Allocated only if `internStrings` is set to true on the constructor.
- Map<String, int> _strings;
+ Map<String, int>? _strings;
/// Creates a new FlatBuffers Builder.
///
@@ -142,18 +148,28 @@
/// automatically grow the array if/as needed. `internStrings`, if set to
/// true, will cause [writeString] to pool strings in the buffer so that
/// identical strings will always use the same offset in tables.
- Builder({this.initialSize: 1024, bool internStrings = false}) {
- if (internStrings == true) {
- _strings = new Map<String, int>();
+ Builder({
+ this.initialSize = 1024,
+ bool internStrings = false,
+ Allocator allocator = const DefaultAllocator(),
+ this.deduplicateTables = true,
+ }) : _allocator = allocator,
+ _buf = allocator.allocate(initialSize),
+ _vTables = deduplicateTables ? [] : const [] {
+ if (internStrings) {
+ _strings = <String, int>{};
}
- reset();
}
+ /// Calculate the finished buffer size (aligned).
+ @pragma('vm:prefer-inline')
+ int size() => _tail + ((-_tail) & (_maxAlign - 1));
+
/// Add the [field] with the given boolean [value]. The field is not added if
/// the [value] is equal to [def]. Booleans are stored as 8-bit fields with
/// `0` for `false` and `1` for `true`.
- void addBool(int field, bool value, [bool def]) {
- _ensureCurrentVTable();
+ void addBool(int field, bool? value, [bool? def]) {
+ assert(_inVTable);
if (value != null && value != def) {
_prepare(_sizeofUint8, 1);
_trackField(field);
@@ -163,180 +179,183 @@
/// Add the [field] with the given 32-bit signed integer [value]. The field is
/// not added if the [value] is equal to [def].
- void addInt32(int field, int value, [int def]) {
- _ensureCurrentVTable();
+ void addInt32(int field, int? value, [int? def]) {
+ assert(_inVTable);
if (value != null && value != def) {
_prepare(_sizeofInt32, 1);
_trackField(field);
- _setInt32AtTail(_buf, _tail, value);
+ _setInt32AtTail(_tail, value);
}
}
/// Add the [field] with the given 32-bit signed integer [value]. The field is
/// not added if the [value] is equal to [def].
- void addInt16(int field, int value, [int def]) {
- _ensureCurrentVTable();
+ void addInt16(int field, int? value, [int? def]) {
+ assert(_inVTable);
if (value != null && value != def) {
_prepare(_sizeofInt16, 1);
_trackField(field);
- _setInt16AtTail(_buf, _tail, value);
+ _setInt16AtTail(_tail, value);
}
}
/// Add the [field] with the given 8-bit signed integer [value]. The field is
/// not added if the [value] is equal to [def].
- void addInt8(int field, int value, [int def]) {
- _ensureCurrentVTable();
+ void addInt8(int field, int? value, [int? def]) {
+ assert(_inVTable);
if (value != null && value != def) {
_prepare(_sizeofInt8, 1);
_trackField(field);
- _setInt8AtTail(_buf, _tail, value);
+ _setInt8AtTail(_tail, value);
}
}
void addStruct(int field, int offset) {
- _ensureCurrentVTable();
+ assert(_inVTable);
_trackField(field);
- _currentVTable.addField(field, offset);
+ _currentVTable!.addField(field, offset);
}
/// Add the [field] referencing an object with the given [offset].
- void addOffset(int field, int offset) {
- _ensureCurrentVTable();
+ void addOffset(int field, int? offset) {
+ assert(_inVTable);
if (offset != null) {
_prepare(_sizeofUint32, 1);
_trackField(field);
- _setUint32AtTail(_buf, _tail, _tail - offset);
+ _setUint32AtTail(_tail, _tail - offset);
}
}
/// Add the [field] with the given 32-bit unsigned integer [value]. The field
/// is not added if the [value] is equal to [def].
- void addUint32(int field, int value, [int def]) {
- _ensureCurrentVTable();
+ void addUint32(int field, int? value, [int? def]) {
+ assert(_inVTable);
if (value != null && value != def) {
_prepare(_sizeofUint32, 1);
_trackField(field);
- _setUint32AtTail(_buf, _tail, value);
+ _setUint32AtTail(_tail, value);
}
}
/// Add the [field] with the given 32-bit unsigned integer [value]. The field
/// is not added if the [value] is equal to [def].
- void addUint16(int field, int value, [int def]) {
- _ensureCurrentVTable();
+ void addUint16(int field, int? value, [int? def]) {
+ assert(_inVTable);
if (value != null && value != def) {
_prepare(_sizeofUint16, 1);
_trackField(field);
- _setUint16AtTail(_buf, _tail, value);
+ _setUint16AtTail(_tail, value);
}
}
/// Add the [field] with the given 8-bit unsigned integer [value]. The field
/// is not added if the [value] is equal to [def].
- void addUint8(int field, int value, [int def]) {
- _ensureCurrentVTable();
+ void addUint8(int field, int? value, [int? def]) {
+ assert(_inVTable);
if (value != null && value != def) {
_prepare(_sizeofUint8, 1);
_trackField(field);
- _setUint8AtTail(_buf, _tail, value);
+ _setUint8AtTail(_tail, value);
}
}
/// Add the [field] with the given 32-bit float [value]. The field
/// is not added if the [value] is equal to [def].
- void addFloat32(int field, double value, [double def]) {
- _ensureCurrentVTable();
+ void addFloat32(int field, double? value, [double? def]) {
+ assert(_inVTable);
if (value != null && value != def) {
_prepare(_sizeofFloat32, 1);
_trackField(field);
- _setFloat32AtTail(_buf, _tail, value);
+ _setFloat32AtTail(_tail, value);
}
}
/// Add the [field] with the given 64-bit double [value]. The field
/// is not added if the [value] is equal to [def].
- void addFloat64(int field, double value, [double def]) {
- _ensureCurrentVTable();
+ void addFloat64(int field, double? value, [double? def]) {
+ assert(_inVTable);
if (value != null && value != def) {
_prepare(_sizeofFloat64, 1);
_trackField(field);
- _setFloat64AtTail(_buf, _tail, value);
+ _setFloat64AtTail(_tail, value);
}
}
/// Add the [field] with the given 64-bit unsigned integer [value]. The field
/// is not added if the [value] is equal to [def].
- void addUint64(int field, int value, [double def]) {
- _ensureCurrentVTable();
+ void addUint64(int field, int? value, [double? def]) {
+ assert(_inVTable);
if (value != null && value != def) {
_prepare(_sizeofUint64, 1);
_trackField(field);
- _setUint64AtTail(_buf, _tail, value);
+ _setUint64AtTail(_tail, value);
}
}
/// Add the [field] with the given 64-bit unsigned integer [value]. The field
/// is not added if the [value] is equal to [def].
- void addInt64(int field, int value, [double def]) {
- _ensureCurrentVTable();
+ void addInt64(int field, int? value, [double? def]) {
+ assert(_inVTable);
if (value != null && value != def) {
_prepare(_sizeofInt64, 1);
_trackField(field);
- _setInt64AtTail(_buf, _tail, value);
+ _setInt64AtTail(_tail, value);
}
}
/// End the current table and return its offset.
int endTable() {
- if (_currentVTable == null) {
- throw new StateError('Start a table before ending it.');
- }
+ assert(_inVTable);
// Prepare for writing the VTable.
_prepare(_sizeofInt32, 1);
- int tableTail = _tail;
+ var tableTail = _tail;
// Prepare the size of the current table.
- _currentVTable.tableSize = tableTail - _currentTableEndTail;
+ final currentVTable = _currentVTable!;
+ currentVTable.tableSize = tableTail - _currentTableEndTail;
// Prepare the VTable to use for the current table.
- int vTableTail;
+ int? vTableTail;
{
- _currentVTable.computeFieldOffsets(tableTail);
- // Try to find an existing compatible VTable.
- // Search backward - more likely to have recently used one
- for (int i = _vTables.length - 1; i >= 0; i--) {
- final int vt2Offset = _vTables[i];
- final int vt2Start = _buf.lengthInBytes - vt2Offset;
- final int vt2Size = _buf.getUint16(vt2Start, Endian.little);
+ currentVTable.computeFieldOffsets(tableTail);
- if (_currentVTable._vTableSize == vt2Size &&
- _currentVTable._offsetsMatch(vt2Start, _buf)) {
- vTableTail = vt2Offset;
- break;
+ // Try to find an existing compatible VTable.
+ if (deduplicateTables) {
+ // Search backward - more likely to have recently used one
+ for (var i = _vTables.length - 1; i >= 0; i--) {
+ final vt2Offset = _vTables[i];
+ final vt2Start = _buf.lengthInBytes - vt2Offset;
+ final vt2Size = _buf.getUint16(vt2Start, Endian.little);
+
+ if (currentVTable._vTableSize == vt2Size &&
+ currentVTable._offsetsMatch(vt2Start, _buf)) {
+ vTableTail = vt2Offset;
+ break;
+ }
}
}
+
// Write a new VTable.
if (vTableTail == null) {
- _prepare(_sizeofUint16, _currentVTable.numOfUint16);
+ _prepare(_sizeofUint16, _currentVTable!.numOfUint16);
vTableTail = _tail;
- _currentVTable.tail = vTableTail;
- _currentVTable.output(_buf, _buf.lengthInBytes - _tail);
- _vTables.add(_currentVTable.tail);
+ currentVTable.tail = vTableTail;
+ currentVTable.output(_buf, _buf.lengthInBytes - _tail);
+ if (deduplicateTables) _vTables.add(currentVTable.tail);
}
}
// Set the VTable offset.
- _setInt32AtTail(_buf, tableTail, vTableTail - tableTail);
+ _setInt32AtTail(tableTail, vTableTail - tableTail);
// Done with this table.
_currentVTable = null;
return tableTail;
}
- /// This method low level method can be used to return a raw piece of the buffer
- /// after using the the put* methods.
- ///
- /// Most clients should prefer calling [finish].
- Uint8List lowFinish() {
- int alignedTail = _tail + ((-_tail) % _maxAlign);
- return _buf.buffer.asUint8List(_buf.lengthInBytes - alignedTail);
+ /// Returns the finished buffer. You must call [finish] before accessing this.
+ @pragma('vm:prefer-inline')
+ Uint8List get buffer {
+ assert(_finished);
+ final finishedSize = size();
+ return _buf.buffer
+ .asUint8List(_buf.lengthInBytes - finishedSize, finishedSize);
}
/// Finish off the creation of the buffer. The given [offset] is used as the
@@ -344,17 +363,26 @@
/// written object. If [fileIdentifier] is specified (and not `null`), it is
/// interpreted as a 4-byte Latin-1 encoded string that should be placed at
/// bytes 4-7 of the file.
- Uint8List finish(int offset, [String fileIdentifier]) {
- _prepare(max(_sizeofUint32, _maxAlign), fileIdentifier == null ? 1 : 2);
- int alignedTail = _tail + ((-_tail) % _maxAlign);
- _setUint32AtTail(_buf, alignedTail, alignedTail - offset);
+ void finish(int offset, [String? fileIdentifier]) {
+ final sizeBeforePadding = size();
+ final requiredBytes = _sizeofUint32 * (fileIdentifier == null ? 1 : 2);
+ _prepare(max(requiredBytes, _maxAlign), 1);
+ final finishedSize = size();
+ _setUint32AtTail(finishedSize, finishedSize - offset);
if (fileIdentifier != null) {
- for (int i = 0; i < 4; i++) {
- _setUint8AtTail(_buf, alignedTail - _sizeofUint32 - i,
- fileIdentifier.codeUnitAt(i));
+ for (var i = 0; i < 4; i++) {
+ _setUint8AtTail(
+ finishedSize - _sizeofUint32 - i, fileIdentifier.codeUnitAt(i));
}
}
- return _buf.buffer.asUint8List(_buf.lengthInBytes - alignedTail);
+
+ // zero out the added padding
+ for (var i = sizeBeforePadding + 1;
+ i <= finishedSize - requiredBytes;
+ i++) {
+ _setUint8AtTail(i, 0);
+ }
+ _finished = true;
}
/// Writes a Float64 to the tail of the buffer after preparing space for it.
@@ -362,7 +390,7 @@
/// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer.
void putFloat64(double value) {
_prepare(_sizeofFloat64, 1);
- _setFloat32AtTail(_buf, _tail, value);
+ _setFloat32AtTail(_tail, value);
}
/// Writes a Float32 to the tail of the buffer after preparing space for it.
@@ -370,7 +398,7 @@
/// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer.
void putFloat32(double value) {
_prepare(_sizeofFloat32, 1);
- _setFloat32AtTail(_buf, _tail, value);
+ _setFloat32AtTail(_tail, value);
}
/// Writes a Int64 to the tail of the buffer after preparing space for it.
@@ -378,7 +406,7 @@
/// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer.
void putInt64(int value) {
_prepare(_sizeofInt64, 1);
- _setInt64AtTail(_buf, _tail, value);
+ _setInt64AtTail(_tail, value);
}
/// Writes a Uint32 to the tail of the buffer after preparing space for it.
@@ -386,7 +414,7 @@
/// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer.
void putInt32(int value) {
_prepare(_sizeofInt32, 1);
- _setInt32AtTail(_buf, _tail, value);
+ _setInt32AtTail(_tail, value);
}
/// Writes a Uint16 to the tail of the buffer after preparing space for it.
@@ -394,7 +422,7 @@
/// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer.
void putInt16(int value) {
_prepare(_sizeofInt16, 1);
- _setInt16AtTail(_buf, _tail, value);
+ _setInt16AtTail(_tail, value);
}
/// Writes a Uint8 to the tail of the buffer after preparing space for it.
@@ -410,7 +438,7 @@
/// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer.
void putUint64(int value) {
_prepare(_sizeofUint64, 1);
- _setUint64AtTail(_buf, _tail, value);
+ _setUint64AtTail(_tail, value);
}
/// Writes a Uint32 to the tail of the buffer after preparing space for it.
@@ -418,7 +446,7 @@
/// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer.
void putUint32(int value) {
_prepare(_sizeofUint32, 1);
- _setUint32AtTail(_buf, _tail, value);
+ _setUint32AtTail(_tail, value);
}
/// Writes a Uint16 to the tail of the buffer after preparing space for it.
@@ -426,7 +454,7 @@
/// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer.
void putUint16(int value) {
_prepare(_sizeofUint16, 1);
- _setUint16AtTail(_buf, _tail, value);
+ _setUint16AtTail(_tail, value);
}
/// Writes a Uint8 to the tail of the buffer after preparing space for it.
@@ -439,21 +467,20 @@
/// Reset the builder and make it ready for filling a new buffer.
void reset() {
- _buf = new ByteData(initialSize);
+ _finished = false;
_maxAlign = 1;
_tail = 0;
_currentVTable = null;
+ if (deduplicateTables) _vTables.clear();
if (_strings != null) {
- _strings = new Map<String, int>();
+ _strings = <String, int>{};
}
}
- /// Start a new table. Must be finished with [endTable] invocation.
- void startTable() {
- if (_currentVTable != null) {
- throw new StateError('Inline tables are not supported.');
- }
- _currentVTable = new _VTable();
+ /// Start a new table. Must be finished with [endTable] invocation.
+ void startTable(int numFields) {
+ assert(!_inVTable); // Inline tables are not supported.
+ _currentVTable = _VTable(numFields);
_currentTableEndTail = _tail;
}
@@ -467,8 +494,8 @@
/// Writes a list of Structs to the buffer, returning the offset
int writeListOfStructs(List<ObjectBuilder> structBuilders) {
- _ensureNoVTable();
- for (int i = structBuilders.length - 1; i >= 0; i--) {
+ assert(!_inVTable);
+ for (var i = structBuilders.length - 1; i >= 0; i--) {
structBuilders[i].finish(this);
}
return endStructVector(structBuilders.length);
@@ -476,14 +503,14 @@
/// Write the given list of [values].
int writeList(List<int> values) {
- _ensureNoVTable();
+ assert(!_inVTable);
_prepare(_sizeofUint32, 1 + values.length);
- final int result = _tail;
- int tail = _tail;
- _setUint32AtTail(_buf, tail, values.length);
+ final result = _tail;
+ var tail = _tail;
+ _setUint32AtTail(tail, values.length);
tail -= _sizeofUint32;
- for (int value in values) {
- _setUint32AtTail(_buf, tail, tail - value);
+ for (var value in values) {
+ _setUint32AtTail(tail, tail - value);
tail -= _sizeofUint32;
}
return result;
@@ -491,14 +518,14 @@
/// Write the given list of 64-bit float [values].
int writeListFloat64(List<double> values) {
- _ensureNoVTable();
+ assert(!_inVTable);
_prepare(_sizeofFloat64, values.length, additionalBytes: _sizeofUint32);
- final int result = _tail;
- int tail = _tail;
- _setUint32AtTail(_buf, tail, values.length);
+ final result = _tail;
+ var tail = _tail;
+ _setUint32AtTail(tail, values.length);
tail -= _sizeofUint32;
- for (double value in values) {
- _setFloat64AtTail(_buf, tail, value);
+ for (var value in values) {
+ _setFloat64AtTail(tail, value);
tail -= _sizeofFloat64;
}
return result;
@@ -506,14 +533,14 @@
/// Write the given list of 32-bit float [values].
int writeListFloat32(List<double> values) {
- _ensureNoVTable();
+ assert(!_inVTable);
_prepare(_sizeofFloat32, 1 + values.length);
- final int result = _tail;
- int tail = _tail;
- _setUint32AtTail(_buf, tail, values.length);
+ final result = _tail;
+ var tail = _tail;
+ _setUint32AtTail(tail, values.length);
tail -= _sizeofUint32;
- for (double value in values) {
- _setFloat32AtTail(_buf, tail, value);
+ for (var value in values) {
+ _setFloat32AtTail(tail, value);
tail -= _sizeofFloat32;
}
return result;
@@ -521,14 +548,14 @@
/// Write the given list of signed 64-bit integer [values].
int writeListInt64(List<int> values) {
- _ensureNoVTable();
+ assert(!_inVTable);
_prepare(_sizeofInt64, values.length, additionalBytes: _sizeofUint32);
- final int result = _tail;
- int tail = _tail;
- _setUint32AtTail(_buf, tail, values.length);
+ final result = _tail;
+ var tail = _tail;
+ _setUint32AtTail(tail, values.length);
tail -= _sizeofUint32;
- for (int value in values) {
- _setInt64AtTail(_buf, tail, value);
+ for (var value in values) {
+ _setInt64AtTail(tail, value);
tail -= _sizeofInt64;
}
return result;
@@ -536,14 +563,14 @@
/// Write the given list of signed 64-bit integer [values].
int writeListUint64(List<int> values) {
- _ensureNoVTable();
+ assert(!_inVTable);
_prepare(_sizeofUint64, values.length, additionalBytes: _sizeofUint32);
- final int result = _tail;
- int tail = _tail;
- _setUint32AtTail(_buf, tail, values.length);
+ final result = _tail;
+ var tail = _tail;
+ _setUint32AtTail(tail, values.length);
tail -= _sizeofUint32;
- for (int value in values) {
- _setUint64AtTail(_buf, tail, value);
+ for (var value in values) {
+ _setUint64AtTail(tail, value);
tail -= _sizeofUint64;
}
return result;
@@ -551,14 +578,14 @@
/// Write the given list of signed 32-bit integer [values].
int writeListInt32(List<int> values) {
- _ensureNoVTable();
+ assert(!_inVTable);
_prepare(_sizeofUint32, 1 + values.length);
- final int result = _tail;
- int tail = _tail;
- _setUint32AtTail(_buf, tail, values.length);
+ final result = _tail;
+ var tail = _tail;
+ _setUint32AtTail(tail, values.length);
tail -= _sizeofUint32;
- for (int value in values) {
- _setInt32AtTail(_buf, tail, value);
+ for (var value in values) {
+ _setInt32AtTail(tail, value);
tail -= _sizeofInt32;
}
return result;
@@ -566,14 +593,14 @@
/// Write the given list of unsigned 32-bit integer [values].
int writeListUint32(List<int> values) {
- _ensureNoVTable();
+ assert(!_inVTable);
_prepare(_sizeofUint32, 1 + values.length);
- final int result = _tail;
- int tail = _tail;
- _setUint32AtTail(_buf, tail, values.length);
+ final result = _tail;
+ var tail = _tail;
+ _setUint32AtTail(tail, values.length);
tail -= _sizeofUint32;
- for (int value in values) {
- _setUint32AtTail(_buf, tail, value);
+ for (var value in values) {
+ _setUint32AtTail(tail, value);
tail -= _sizeofUint32;
}
return result;
@@ -581,14 +608,14 @@
/// Write the given list of signed 16-bit integer [values].
int writeListInt16(List<int> values) {
- _ensureNoVTable();
+ assert(!_inVTable);
_prepare(_sizeofUint32, 1, additionalBytes: 2 * values.length);
- final int result = _tail;
- int tail = _tail;
- _setUint32AtTail(_buf, tail, values.length);
+ final result = _tail;
+ var tail = _tail;
+ _setUint32AtTail(tail, values.length);
tail -= _sizeofUint32;
- for (int value in values) {
- _setInt16AtTail(_buf, tail, value);
+ for (var value in values) {
+ _setInt16AtTail(tail, value);
tail -= _sizeofInt16;
}
return result;
@@ -596,14 +623,14 @@
/// Write the given list of unsigned 16-bit integer [values].
int writeListUint16(List<int> values) {
- _ensureNoVTable();
+ assert(!_inVTable);
_prepare(_sizeofUint32, 1, additionalBytes: 2 * values.length);
- final int result = _tail;
- int tail = _tail;
- _setUint32AtTail(_buf, tail, values.length);
+ final result = _tail;
+ var tail = _tail;
+ _setUint32AtTail(tail, values.length);
tail -= _sizeofUint32;
- for (int value in values) {
- _setUint16AtTail(_buf, tail, value);
+ for (var value in values) {
+ _setUint16AtTail(tail, value);
tail -= _sizeofUint16;
}
return result;
@@ -611,19 +638,19 @@
/// Write the given list of bools as unsigend 8-bit integer [values].
int writeListBool(List<bool> values) {
- return writeListUint8(values?.map((b) => b ? 1 : 0)?.toList());
+ return writeListUint8(values.map((b) => b ? 1 : 0).toList());
}
/// Write the given list of signed 8-bit integer [values].
int writeListInt8(List<int> values) {
- _ensureNoVTable();
+ assert(!_inVTable);
_prepare(_sizeofUint32, 1, additionalBytes: values.length);
- final int result = _tail;
- int tail = _tail;
- _setUint32AtTail(_buf, tail, values.length);
+ final result = _tail;
+ var tail = _tail;
+ _setUint32AtTail(tail, values.length);
tail -= _sizeofUint32;
- for (int value in values) {
- _setInt8AtTail(_buf, tail, value);
+ for (var value in values) {
+ _setInt8AtTail(tail, value);
tail -= _sizeofUint8;
}
return result;
@@ -631,146 +658,187 @@
/// Write the given list of unsigned 8-bit integer [values].
int writeListUint8(List<int> values) {
- _ensureNoVTable();
+ assert(!_inVTable);
_prepare(_sizeofUint32, 1, additionalBytes: values.length);
- final int result = _tail;
- int tail = _tail;
- _setUint32AtTail(_buf, tail, values.length);
+ final result = _tail;
+ var tail = _tail;
+ _setUint32AtTail(tail, values.length);
tail -= _sizeofUint32;
- for (int value in values) {
- _setUint8AtTail(_buf, tail, value);
+ for (var value in values) {
+ _setUint8AtTail(tail, value);
tail -= _sizeofUint8;
}
return result;
}
- /// Write the given string [value] and return its offset, or `null` if
- /// the [value] is `null`.
- int writeString(String value) {
- _ensureNoVTable();
- if (value != null) {
- if (_strings != null) {
- return _strings.putIfAbsent(value, () => _writeString(value));
- } else {
- return _writeString(value);
- }
+ /// Write the given string [value] and return its offset.
+ ///
+ /// Dart strings are UTF-16 but must be stored as UTF-8 in FlatBuffers.
+ /// If the given string consists only of ASCII characters, you can indicate
+ /// enable [asciiOptimization]. In this mode, [writeString()] first tries to
+ /// copy the ASCII string directly to the output buffer and if that fails
+ /// (because there are no-ASCII characters in the string) it falls back and to
+ /// the default UTF-16 -> UTF-8 conversion (with slight performance penalty).
+ int writeString(String value, {bool asciiOptimization = false}) {
+ assert(!_inVTable);
+ if (_strings != null) {
+ return _strings!
+ .putIfAbsent(value, () => _writeString(value, asciiOptimization));
+ } else {
+ return _writeString(value, asciiOptimization);
}
- return null;
}
- int _writeString(String value) {
- // TODO(scheglov) optimize for ASCII strings
- List<int> bytes = utf8.encode(value);
- int length = bytes.length;
+ int _writeString(String value, bool asciiOptimization) {
+ if (asciiOptimization) {
+ // [utf8.encode()] is slow (up to at least Dart SDK 2.13). If the given
+ // string is ASCII we can just write it directly, without any conversion.
+ final originalTail = _tail;
+ if (_tryWriteASCIIString(value)) return _tail;
+ // if non-ASCII: reset the output buffer position for [_writeUTFString()]
+ _tail = originalTail;
+ }
+ _writeUTFString(value);
+ return _tail;
+ }
+
+ // Try to write the string as ASCII, return false if there's a non-ascii char.
+ @pragma('vm:prefer-inline')
+ bool _tryWriteASCIIString(String value) {
+ _prepare(4, 1, additionalBytes: value.length + 1);
+ final length = value.length;
+ var offset = _buf.lengthInBytes - _tail + 4;
+ for (var i = 0; i < length; i++) {
+ // utf16 code unit, e.g. for '†' it's [0x20 0x20], which is 8224 decimal.
+ // ASCII characters go from 0x00 to 0x7F (which is 0 to 127 decimal).
+ final char = value.codeUnitAt(i);
+ if ((char & ~0x7F) != 0) {
+ return false;
+ }
+ _buf.setUint8(offset++, char);
+ }
+ _buf.setUint8(offset, 0); // trailing zero
+ _setUint32AtTail(_tail, value.length);
+ return true;
+ }
+
+ @pragma('vm:prefer-inline')
+ void _writeUTFString(String value) {
+ final bytes = utf8.encode(value) as Uint8List;
+ final length = bytes.length;
_prepare(4, 1, additionalBytes: length + 1);
- final int result = _tail;
- _setUint32AtTail(_buf, _tail, length);
- int offset = _buf.lengthInBytes - _tail + 4;
- for (int i = 0; i < length; i++) {
+ _setUint32AtTail(_tail, length);
+ var offset = _buf.lengthInBytes - _tail + 4;
+ for (var i = 0; i < length; i++) {
_buf.setUint8(offset++, bytes[i]);
}
- return result;
+ _buf.setUint8(offset, 0); // trailing zero
}
- /// Throw an exception if there is not currently a vtable.
- void _ensureCurrentVTable() {
- if (_currentVTable == null) {
- throw new StateError('Start a table before adding values.');
- }
- }
-
- /// Throw an exception if there is currently a vtable.
- void _ensureNoVTable() {
- if (_currentVTable != null) {
- throw new StateError(
- 'Cannot write a non-scalar value while writing a table.');
- }
- }
+ /// Used to assert whether a "Table" is currently being built.
+ ///
+ /// If you hit `assert(!_inVTable())`, you're trying to add table fields
+ /// without starting a table with [Builder.startTable()].
+ ///
+ /// If you hit `assert(_inVTable())`, you're trying to construct a
+ /// Table/Vector/String during the construction of its parent table,
+ /// between the MyTableBuilder and [Builder.endTable()].
+ /// Move the creation of these sub-objects to before the MyTableBuilder to
+ /// not get this assert.
+ @pragma('vm:prefer-inline')
+ bool get _inVTable => _currentVTable != null;
/// The number of bytes that have been written to the buffer so far. The
/// most recently written byte is this many bytes from the end of the buffer.
+ @pragma('vm:prefer-inline')
int get offset => _tail;
/// Zero-pads the buffer, which may be required for some struct layouts.
+ @pragma('vm:prefer-inline')
void pad(int howManyBytes) {
- for (int i = 0; i < howManyBytes; i++) putUint8(0);
+ for (var i = 0; i < howManyBytes; i++) {
+ putUint8(0);
+ }
}
/// Prepare for writing the given `count` of scalars of the given `size`.
/// Additionally allocate the specified `additionalBytes`. Update the current
/// tail pointer to point at the allocated space.
+ @pragma('vm:prefer-inline')
void _prepare(int size, int count, {int additionalBytes = 0}) {
+ assert(!_finished);
// Update the alignment.
if (_maxAlign < size) {
_maxAlign = size;
}
// Prepare amount of required space.
- int dataSize = size * count + additionalBytes;
- int alignDelta = (-(_tail + dataSize)) % size;
- int bufSize = alignDelta + dataSize;
+ var dataSize = size * count + additionalBytes;
+ var alignDelta = (-(_tail + dataSize)) & (size - 1);
+ var bufSize = alignDelta + dataSize;
// Ensure that we have the required amount of space.
{
- int oldCapacity = _buf.lengthInBytes;
+ var oldCapacity = _buf.lengthInBytes;
if (_tail + bufSize > oldCapacity) {
- int desiredNewCapacity = (oldCapacity + bufSize) * 2;
- int deltaCapacity = desiredNewCapacity - oldCapacity;
- deltaCapacity += (-deltaCapacity) % _maxAlign;
- int newCapacity = oldCapacity + deltaCapacity;
- ByteData newBuf = new ByteData(newCapacity);
- newBuf.buffer
- .asUint8List()
- .setAll(deltaCapacity, _buf.buffer.asUint8List());
- _buf = newBuf;
+ var desiredNewCapacity = (oldCapacity + bufSize) * 2;
+ var deltaCapacity = desiredNewCapacity - oldCapacity;
+ deltaCapacity += (-deltaCapacity) & (_maxAlign - 1);
+ var newCapacity = oldCapacity + deltaCapacity;
+ _buf = _allocator.resize(_buf, newCapacity, _tail, 0);
}
}
+
+ // zero out the added padding
+ for (var i = _tail + 1; i <= _tail + alignDelta; i++) {
+ _setUint8AtTail(i, 0);
+ }
+
// Update the tail pointer.
_tail += bufSize;
}
/// Record the offset of the given [field].
- void _trackField(int field) {
- _currentVTable.addField(field, _tail);
- }
+ @pragma('vm:prefer-inline')
+ void _trackField(int field) => _currentVTable!.addField(field, _tail);
- static void _setFloat64AtTail(ByteData _buf, int tail, double x) {
- _buf.setFloat64(_buf.lengthInBytes - tail, x, Endian.little);
- }
+ @pragma('vm:prefer-inline')
+ void _setFloat64AtTail(int tail, double x) =>
+ _buf.setFloat64(_buf.lengthInBytes - tail, x, Endian.little);
- static void _setFloat32AtTail(ByteData _buf, int tail, double x) {
- _buf.setFloat32(_buf.lengthInBytes - tail, x, Endian.little);
- }
+ @pragma('vm:prefer-inline')
+ void _setFloat32AtTail(int tail, double x) =>
+ _buf.setFloat32(_buf.lengthInBytes - tail, x, Endian.little);
- static void _setUint64AtTail(ByteData _buf, int tail, int x) {
- _buf.setUint64(_buf.lengthInBytes - tail, x, Endian.little);
- }
+ @pragma('vm:prefer-inline')
+ void _setUint64AtTail(int tail, int x) =>
+ _buf.setUint64(_buf.lengthInBytes - tail, x, Endian.little);
- static void _setInt64AtTail(ByteData _buf, int tail, int x) {
- _buf.setInt64(_buf.lengthInBytes - tail, x, Endian.little);
- }
+ @pragma('vm:prefer-inline')
+ void _setInt64AtTail(int tail, int x) =>
+ _buf.setInt64(_buf.lengthInBytes - tail, x, Endian.little);
- static void _setInt32AtTail(ByteData _buf, int tail, int x) {
- _buf.setInt32(_buf.lengthInBytes - tail, x, Endian.little);
- }
+ @pragma('vm:prefer-inline')
+ void _setInt32AtTail(int tail, int x) =>
+ _buf.setInt32(_buf.lengthInBytes - tail, x, Endian.little);
- static void _setUint32AtTail(ByteData _buf, int tail, int x) {
- _buf.setUint32(_buf.lengthInBytes - tail, x, Endian.little);
- }
+ @pragma('vm:prefer-inline')
+ void _setUint32AtTail(int tail, int x) =>
+ _buf.setUint32(_buf.lengthInBytes - tail, x, Endian.little);
- static void _setInt16AtTail(ByteData _buf, int tail, int x) {
- _buf.setInt16(_buf.lengthInBytes - tail, x, Endian.little);
- }
+ @pragma('vm:prefer-inline')
+ void _setInt16AtTail(int tail, int x) =>
+ _buf.setInt16(_buf.lengthInBytes - tail, x, Endian.little);
- static void _setUint16AtTail(ByteData _buf, int tail, int x) {
- _buf.setUint16(_buf.lengthInBytes - tail, x, Endian.little);
- }
+ @pragma('vm:prefer-inline')
+ void _setUint16AtTail(int tail, int x) =>
+ _buf.setUint16(_buf.lengthInBytes - tail, x, Endian.little);
- static void _setInt8AtTail(ByteData _buf, int tail, int x) {
- _buf.setInt8(_buf.lengthInBytes - tail, x);
- }
+ @pragma('vm:prefer-inline')
+ void _setInt8AtTail(int tail, int x) =>
+ _buf.setInt8(_buf.lengthInBytes - tail, x);
- static void _setUint8AtTail(ByteData _buf, int tail, int x) {
- _buf.setUint8(_buf.lengthInBytes - tail, x);
- }
+ @pragma('vm:prefer-inline')
+ void _setUint8AtTail(int tail, int x) =>
+ _buf.setUint8(_buf.lengthInBytes - tail, x);
}
/// Reader of lists of boolean values.
@@ -780,11 +848,13 @@
const BoolListReader();
@override
+ @pragma('vm:prefer-inline')
int get size => _sizeofUint32;
@override
+ @pragma('vm:prefer-inline')
List<bool> read(BufferContext bc, int offset) =>
- new _FbBoolList(bc, bc.derefObject(offset));
+ _FbBoolList(bc, bc.derefObject(offset));
}
/// The reader of booleans.
@@ -792,9 +862,11 @@
const BoolReader() : super();
@override
+ @pragma('vm:prefer-inline')
int get size => _sizeofUint8;
@override
+ @pragma('vm:prefer-inline')
bool read(BufferContext bc, int offset) => bc._getInt8(offset) != 0;
}
@@ -805,31 +877,37 @@
const Float64ListReader();
@override
+ @pragma('vm:prefer-inline')
int get size => _sizeofFloat64;
@override
+ @pragma('vm:prefer-inline')
List<double> read(BufferContext bc, int offset) =>
- new _FbFloat64List(bc, bc.derefObject(offset));
+ _FbFloat64List(bc, bc.derefObject(offset));
}
class Float32ListReader extends Reader<List<double>> {
const Float32ListReader();
@override
+ @pragma('vm:prefer-inline')
int get size => _sizeofFloat32;
@override
+ @pragma('vm:prefer-inline')
List<double> read(BufferContext bc, int offset) =>
- new _FbFloat32List(bc, bc.derefObject(offset));
+ _FbFloat32List(bc, bc.derefObject(offset));
}
class Float64Reader extends Reader<double> {
const Float64Reader();
@override
+ @pragma('vm:prefer-inline')
int get size => _sizeofFloat64;
@override
+ @pragma('vm:prefer-inline')
double read(BufferContext bc, int offset) => bc._getFloat64(offset);
}
@@ -837,18 +915,23 @@
const Float32Reader();
@override
+ @pragma('vm:prefer-inline')
int get size => _sizeofFloat32;
@override
+ @pragma('vm:prefer-inline')
double read(BufferContext bc, int offset) => bc._getFloat32(offset);
}
class Int64Reader extends Reader<int> {
const Int64Reader() : super();
+
@override
+ @pragma('vm:prefer-inline')
int get size => _sizeofInt64;
@override
+ @pragma('vm:prefer-inline')
int read(BufferContext bc, int offset) => bc._getInt64(offset);
}
@@ -857,9 +940,11 @@
const Int32Reader() : super();
@override
+ @pragma('vm:prefer-inline')
int get size => _sizeofInt32;
@override
+ @pragma('vm:prefer-inline')
int read(BufferContext bc, int offset) => bc._getInt32(offset);
}
@@ -868,9 +953,11 @@
const Int16Reader() : super();
@override
+ @pragma('vm:prefer-inline')
int get size => _sizeofInt16;
@override
+ @pragma('vm:prefer-inline')
int read(BufferContext bc, int offset) => bc._getInt16(offset);
}
@@ -879,26 +966,43 @@
const Int8Reader() : super();
@override
+ @pragma('vm:prefer-inline')
int get size => _sizeofInt8;
@override
+ @pragma('vm:prefer-inline')
int read(BufferContext bc, int offset) => bc._getInt8(offset);
}
-/// The reader of lists of objects.
-///
-/// The returned unmodifiable lists lazily read objects on access.
+/// The reader of lists of objects. Lazy by default - see [lazy].
class ListReader<E> extends Reader<List<E>> {
final Reader<E> _elementReader;
- const ListReader(this._elementReader);
+ /// Enables lazy reading of the list
+ ///
+ /// If true, the returned unmodifiable list lazily reads objects on access.
+ /// Therefore, the underlying buffer must not change while accessing the list.
+ ///
+ /// If false, reads the whole list immediately on access.
+ final bool lazy;
+
+ const ListReader(this._elementReader, {this.lazy = true});
@override
+ @pragma('vm:prefer-inline')
int get size => _sizeofUint32;
@override
- List<E> read(BufferContext bc, int offset) =>
- new _FbGenericList<E>(_elementReader, bc, bc.derefObject(offset));
+ List<E> read(BufferContext bc, int offset) {
+ final listOffset = bc.derefObject(offset);
+ return lazy
+ ? _FbGenericList<E>(_elementReader, bc, listOffset)
+ : List<E>.generate(
+ bc.buffer.getUint32(listOffset, Endian.little),
+ (int index) => _elementReader.read(
+ bc, listOffset + size + _elementReader.size * index),
+ growable: true);
+ }
}
/// Object that can read a value at a [BufferContext].
@@ -912,43 +1016,55 @@
T read(BufferContext bc, int offset);
/// Read the value of the given [field] in the given [object].
- T vTableGet(BufferContext object, int offset, int field, [T defaultValue]) {
- int vTableSOffset = object._getInt32(offset);
- int vTableOffset = offset - vTableSOffset;
- int vTableSize = object._getUint16(vTableOffset);
- int vTableFieldOffset = field;
- if (vTableFieldOffset < vTableSize) {
- int fieldOffsetInObject =
- object._getUint16(vTableOffset + vTableFieldOffset);
- if (fieldOffsetInObject != 0) {
- return read(object, offset + fieldOffsetInObject);
- }
- }
- return defaultValue;
+ @pragma('vm:prefer-inline')
+ T vTableGet(BufferContext object, int offset, int field, T defaultValue) {
+ var fieldOffset = _vTableFieldOffset(object, offset, field);
+ return fieldOffset == 0 ? defaultValue : read(object, offset + fieldOffset);
+ }
+
+ /// Read the value of the given [field] in the given [object].
+ @pragma('vm:prefer-inline')
+ T? vTableGetNullable(BufferContext object, int offset, int field) {
+ var fieldOffset = _vTableFieldOffset(object, offset, field);
+ return fieldOffset == 0 ? null : read(object, offset + fieldOffset);
+ }
+
+ @pragma('vm:prefer-inline')
+ int _vTableFieldOffset(BufferContext object, int offset, int field) {
+ var vTableSOffset = object._getInt32(offset);
+ var vTableOffset = offset - vTableSOffset;
+ var vTableSize = object._getUint16(vTableOffset);
+ if (field >= vTableSize) return 0;
+ return object._getUint16(vTableOffset + field);
}
}
/// The reader of string values.
class StringReader extends Reader<String> {
- const StringReader() : super();
+ final bool asciiOptimization;
+
+ const StringReader({this.asciiOptimization = false}) : super();
@override
- int get size => 4;
+ @pragma('vm:prefer-inline')
+ int get size => _sizeofUint32;
@override
+ @pragma('vm:prefer-inline')
String read(BufferContext bc, int offset) {
- int strOffset = bc.derefObject(offset);
- int length = bc._getUint32(strOffset);
- Uint8List bytes = bc._asUint8LIst(strOffset + 4, length);
- if (_isLatin(bytes)) {
- return new String.fromCharCodes(bytes);
+ var strOffset = bc.derefObject(offset);
+ var length = bc._getUint32(strOffset);
+ var bytes = bc._asUint8List(strOffset + _sizeofUint32, length);
+ if (asciiOptimization && _isLatin(bytes)) {
+ return String.fromCharCodes(bytes);
}
return utf8.decode(bytes);
}
+ @pragma('vm:prefer-inline')
static bool _isLatin(Uint8List bytes) {
- int length = bytes.length;
- for (int i = 0; i < length; i++) {
+ var length = bytes.length;
+ for (var i = 0; i < length; i++) {
if (bytes[i] > 127) {
return false;
}
@@ -964,8 +1080,9 @@
/// Return the object at `offset`.
T createObject(BufferContext bc, int offset);
- T read(BufferContext bp, int offset) {
- return createObject(bp, offset);
+ @override
+ T read(BufferContext bc, int offset) {
+ return createObject(bc, offset);
}
}
@@ -974,15 +1091,16 @@
const TableReader();
@override
+ @pragma('vm:prefer-inline')
int get size => 4;
/// Return the object at [offset].
T createObject(BufferContext bc, int offset);
@override
- T read(BufferContext bp, int offset) {
- int objectOffset = bp.derefObject(offset);
- return createObject(bp, objectOffset);
+ T read(BufferContext bc, int offset) {
+ var objectOffset = bc.derefObject(offset);
+ return createObject(bc, objectOffset);
}
}
@@ -993,11 +1111,13 @@
const Uint32ListReader();
@override
+ @pragma('vm:prefer-inline')
int get size => _sizeofUint32;
@override
+ @pragma('vm:prefer-inline')
List<int> read(BufferContext bc, int offset) =>
- new _FbUint32List(bc, bc.derefObject(offset));
+ _FbUint32List(bc, bc.derefObject(offset));
}
/// The reader of unsigned 64-bit integers.
@@ -1007,9 +1127,11 @@
const Uint64Reader() : super();
@override
+ @pragma('vm:prefer-inline')
int get size => _sizeofUint64;
@override
+ @pragma('vm:prefer-inline')
int read(BufferContext bc, int offset) => bc._getUint64(offset);
}
@@ -1018,9 +1140,11 @@
const Uint32Reader() : super();
@override
+ @pragma('vm:prefer-inline')
int get size => _sizeofUint32;
@override
+ @pragma('vm:prefer-inline')
int read(BufferContext bc, int offset) => bc._getUint32(offset);
}
@@ -1031,11 +1155,13 @@
const Uint16ListReader();
@override
+ @pragma('vm:prefer-inline')
int get size => _sizeofUint32;
@override
+ @pragma('vm:prefer-inline')
List<int> read(BufferContext bc, int offset) =>
- new _FbUint16List(bc, bc.derefObject(offset));
+ _FbUint16List(bc, bc.derefObject(offset));
}
/// The reader of unsigned 32-bit integers.
@@ -1043,24 +1169,44 @@
const Uint16Reader() : super();
@override
+ @pragma('vm:prefer-inline')
int get size => _sizeofUint16;
@override
+ @pragma('vm:prefer-inline')
int read(BufferContext bc, int offset) => bc._getUint16(offset);
}
-/// Reader of lists of unsigned 8-bit integer values.
-///
-/// The returned unmodifiable lists lazily read values on access.
+/// Reader of unmodifiable binary data (a list of unsigned 8-bit integers).
class Uint8ListReader extends Reader<List<int>> {
- const Uint8ListReader();
+ /// Enables lazy reading of the list
+ ///
+ /// If true, the returned unmodifiable list lazily reads bytes on access.
+ /// Therefore, the underlying buffer must not change while accessing the list.
+ ///
+ /// If false, reads the whole list immediately as an Uint8List.
+ final bool lazy;
+
+ const Uint8ListReader({this.lazy = true});
@override
+ @pragma('vm:prefer-inline')
int get size => _sizeofUint32;
@override
- List<int> read(BufferContext bc, int offset) =>
- new _FbUint8List(bc, bc.derefObject(offset));
+ @pragma('vm:prefer-inline')
+ List<int> read(BufferContext bc, int offset) {
+ final listOffset = bc.derefObject(offset);
+ if (lazy) return _FbUint8List(bc, listOffset);
+
+ final length = bc._getUint32(listOffset);
+ final result = Uint8List(length);
+ var pos = listOffset + _sizeofUint32;
+ for (var i = 0; i < length; i++, pos++) {
+ result[i] = bc._getUint8(pos);
+ }
+ return result;
+ }
}
/// The reader of unsigned 8-bit integers.
@@ -1068,20 +1214,53 @@
const Uint8Reader() : super();
@override
+ @pragma('vm:prefer-inline')
int get size => _sizeofUint8;
@override
+ @pragma('vm:prefer-inline')
int read(BufferContext bc, int offset) => bc._getUint8(offset);
}
+/// Reader of unmodifiable binary data (a list of signed 8-bit integers).
+class Int8ListReader extends Reader<List<int>> {
+ /// Enables lazy reading of the list
+ ///
+ /// If true, the returned unmodifiable list lazily reads bytes on access.
+ /// Therefore, the underlying buffer must not change while accessing the list.
+ ///
+ /// If false, reads the whole list immediately as an Uint8List.
+ final bool lazy;
+
+ const Int8ListReader({this.lazy = true});
+
+ @override
+ @pragma('vm:prefer-inline')
+ int get size => _sizeofUint32;
+
+ @override
+ @pragma('vm:prefer-inline')
+ List<int> read(BufferContext bc, int offset) {
+ final listOffset = bc.derefObject(offset);
+ if (lazy) return _FbUint8List(bc, listOffset);
+
+ final length = bc._getUint32(listOffset);
+ final result = Int8List(length);
+ var pos = listOffset + _sizeofUint32;
+ for (var i = 0; i < length; i++, pos++) {
+ result[i] = bc._getInt8(pos);
+ }
+ return result;
+ }
+}
+
/// The list backed by 64-bit values - Uint64 length and Float64.
class _FbFloat64List extends _FbList<double> {
_FbFloat64List(BufferContext bc, int offset) : super(bc, offset);
@override
- double operator [](int i) {
- return bc._getFloat64(offset + 4 + 8 * i);
- }
+ @pragma('vm:prefer-inline')
+ double operator [](int i) => bc._getFloat64(offset + 4 + 8 * i);
}
/// The list backed by 32-bit values - Float32.
@@ -1089,29 +1268,29 @@
_FbFloat32List(BufferContext bc, int offset) : super(bc, offset);
@override
- double operator [](int i) {
- return bc._getFloat32(offset + 4 + 4 * i);
- }
+ @pragma('vm:prefer-inline')
+ double operator [](int i) => bc._getFloat32(offset + 4 + 4 * i);
}
/// List backed by a generic object which may have any size.
class _FbGenericList<E> extends _FbList<E> {
final Reader<E> elementReader;
- List<E> _items;
+ List<E?>? _items;
_FbGenericList(this.elementReader, BufferContext bp, int offset)
: super(bp, offset);
@override
+ @pragma('vm:prefer-inline')
E operator [](int i) {
- _items ??= new List<E>(length);
- E item = _items[i];
+ _items ??= List<E?>.filled(length, null);
+ var item = _items![i];
if (item == null) {
item = elementReader.read(bc, offset + 4 + elementReader.size * i);
- _items[i] = item;
+ _items![i] = item;
}
- return item;
+ return item!;
}
}
@@ -1119,23 +1298,20 @@
abstract class _FbList<E> extends Object with ListMixin<E> implements List<E> {
final BufferContext bc;
final int offset;
- int _length;
+ int? _length;
_FbList(this.bc, this.offset);
@override
- int get length {
- _length ??= bc._getUint32(offset);
- return _length;
- }
+ @pragma('vm:prefer-inline')
+ int get length => _length ??= bc._getUint32(offset);
@override
- void set length(int i) =>
- throw new StateError('Attempt to modify immutable list');
+ set length(int i) => throw StateError('Attempt to modify immutable list');
@override
void operator []=(int i, E e) =>
- throw new StateError('Attempt to modify immutable list');
+ throw StateError('Attempt to modify immutable list');
}
/// List backed by 32-bit unsigned integers.
@@ -1143,9 +1319,8 @@
_FbUint32List(BufferContext bc, int offset) : super(bc, offset);
@override
- int operator [](int i) {
- return bc._getUint32(offset + 4 + 4 * i);
- }
+ @pragma('vm:prefer-inline')
+ int operator [](int i) => bc._getUint32(offset + 4 + 4 * i);
}
/// List backed by 16-bit unsigned integers.
@@ -1153,9 +1328,8 @@
_FbUint16List(BufferContext bc, int offset) : super(bc, offset);
@override
- int operator [](int i) {
- return bc._getUint16(offset + 4 + 2 * i);
- }
+ @pragma('vm:prefer-inline')
+ int operator [](int i) => bc._getUint16(offset + 4 + 2 * i);
}
/// List backed by 8-bit unsigned integers.
@@ -1163,9 +1337,17 @@
_FbUint8List(BufferContext bc, int offset) : super(bc, offset);
@override
- int operator [](int i) {
- return bc._getUint8(offset + 4 + i);
- }
+ @pragma('vm:prefer-inline')
+ int operator [](int i) => bc._getUint8(offset + 4 + i);
+}
+
+/// List backed by 8-bit signed integers.
+class _FbInt8List extends _FbList<int> {
+ _FbInt8List(BufferContext bc, int offset) : super(bc, offset);
+
+ @override
+ @pragma('vm:prefer-inline')
+ int operator [](int i) => bc._getInt8(offset + 4 + i);
}
/// List backed by 8-bit unsigned integers.
@@ -1173,41 +1355,48 @@
_FbBoolList(BufferContext bc, int offset) : super(bc, offset);
@override
- bool operator [](int i) {
- return bc._getUint8(offset + 4 + i) == 1 ? true : false;
- }
+ @pragma('vm:prefer-inline')
+ bool operator [](int i) => bc._getUint8(offset + 4 + i) == 1 ? true : false;
}
/// Class that describes the structure of a table.
class _VTable {
static const int _metadataLength = 4;
- final List<int> fieldTails = <int>[];
- final List<int> fieldOffsets = <int>[];
+ final int numFields;
+
+ // Note: fieldOffsets start as "tail offsets" and are then transformed by
+ // [computeFieldOffsets()] to actual offsets when a table is finished.
+ final Uint32List fieldOffsets;
+ bool offsetsComputed = false;
+
+ _VTable(this.numFields) : fieldOffsets = Uint32List(numFields);
/// The size of the table that uses this VTable.
- int tableSize;
+ int tableSize = 0;
- /// The tail of this VTable. It is used to share the same VTable between
+ /// The tail of this VTable. It is used to share the same VTable between
/// multiple tables of identical structure.
- int tail;
+ int tail = 0;
int get _vTableSize => numOfUint16 * _sizeofUint16;
- int get numOfUint16 => 1 + 1 + fieldTails.length;
+ int get numOfUint16 => 1 + 1 + numFields;
+ @pragma('vm:prefer-inline')
void addField(int field, int offset) {
- while (fieldTails.length <= field) {
- fieldTails.add(null);
- }
- fieldTails[field] = offset;
+ assert(!offsetsComputed);
+ assert(offset > 0); // it's impossible for field to start at the buffer end
+ assert(offset <= 4294967295); // uint32 max
+ fieldOffsets[field] = offset;
}
+ @pragma('vm:prefer-inline')
bool _offsetsMatch(int vt2Start, ByteData buf) {
- for (int i = 0; i < fieldOffsets.length; i++) {
+ assert(offsetsComputed);
+ for (var i = 0; i < numFields; i++) {
if (fieldOffsets[i] !=
- buf.getUint16(
- vt2Start + _metadataLength + (2 * i), Endian.little)) {
+ buf.getUint16(vt2Start + _metadataLength + (2 * i), Endian.little)) {
return false;
}
}
@@ -1215,17 +1404,22 @@
}
/// Fill the [fieldOffsets] field.
+ @pragma('vm:prefer-inline')
void computeFieldOffsets(int tableTail) {
- assert(fieldOffsets.isEmpty);
- for (int fieldTail in fieldTails) {
- int fieldOffset = fieldTail == null ? 0 : tableTail - fieldTail;
- fieldOffsets.add(fieldOffset);
+ assert(!offsetsComputed);
+ offsetsComputed = true;
+ for (var i = 0; i < numFields; i++) {
+ if (fieldOffsets[i] != 0) {
+ fieldOffsets[i] = tableTail - fieldOffsets[i];
+ }
}
}
/// Outputs this VTable to [buf], which is is expected to be aligned to 16-bit
/// and have at least [numOfUint16] 16-bit words available.
+ @pragma('vm:prefer-inline')
void output(ByteData buf, int bufOffset) {
+ assert(offsetsComputed);
// VTable size.
buf.setUint16(bufOffset, numOfUint16 * 2, Endian.little);
bufOffset += 2;
@@ -1233,9 +1427,62 @@
buf.setUint16(bufOffset, tableSize, Endian.little);
bufOffset += 2;
// Field offsets.
- for (int fieldOffset in fieldOffsets) {
- buf.setUint16(bufOffset, fieldOffset, Endian.little);
+ for (var i = 0; i < numFields; i++) {
+ buf.setUint16(bufOffset, fieldOffsets[i], Endian.little);
bufOffset += 2;
}
}
}
+
+/// The interface that [Builder] uses to allocate buffers for encoding.
+abstract class Allocator {
+ const Allocator();
+
+ /// Allocate a [ByteData] buffer of a given size.
+ ByteData allocate(int size);
+
+ /// Free the given [ByteData] buffer previously allocated by [allocate].
+ void deallocate(ByteData data);
+
+ /// Reallocate [newSize] bytes of memory, replacing the old [oldData]. This
+ /// grows downwards, and is intended specifically for use with [Builder].
+ /// Params [inUseBack] and [inUseFront] indicate how much of [oldData] is
+ /// actually in use at each end, and needs to be copied.
+ ByteData resize(
+ ByteData oldData, int newSize, int inUseBack, int inUseFront) {
+ final newData = allocate(newSize);
+ _copyDownward(oldData, newData, inUseBack, inUseFront);
+ deallocate(oldData);
+ return newData;
+ }
+
+ /// Called by [resize] to copy memory from [oldData] to [newData]. Only
+ /// memory of size [inUseFront] and [inUseBack] will be copied from the front
+ /// and back of the old memory allocation.
+ void _copyDownward(
+ ByteData oldData, ByteData newData, int inUseBack, int inUseFront) {
+ if (inUseBack != 0) {
+ newData.buffer.asUint8List().setAll(
+ newData.lengthInBytes - inUseBack,
+ oldData.buffer.asUint8List().getRange(
+ oldData.lengthInBytes - inUseBack, oldData.lengthInBytes));
+ }
+ if (inUseFront != 0) {
+ newData.buffer
+ .asUint8List()
+ .setAll(0, oldData.buffer.asUint8List().getRange(0, inUseFront));
+ }
+ }
+}
+
+class DefaultAllocator extends Allocator {
+ const DefaultAllocator();
+
+ @override
+ ByteData allocate(int size) => ByteData(size);
+
+ @override
+ void deallocate(ByteData data) {
+ // nothing to do, it's garbage-collected
+ }
+}